is it possible to "update" a QTextCursor?

197 Views Asked by At

In a QTextEdit object, let's say I want to know the character's position under the mouse cursor.

I can write...

void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
  mycursor = this->textCursor();
  qDebug() << "pos=" << mycursor.position();
}

... it works (the mouse position changes from 0 to the last index of the last character) but the mousePressEvent() method creates a new cursor every time an event occurs. It bothers me since I don't know the "cost" of such a creation.

So, why not create a cursor attribute and use it in mousePressEvent() ?

Something like :

class MyQTextEditObject : public QTextEdit {
    Q_OBJECT
public:
    // [...]
    QTextCursor cursor;
}

MyQTextEditObject::MyQTextEditObject(QWidget* parent) : QTextEdit(parent) {
 // [...]
 this->cursor = this->textCursor();
}

void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
  qDebug() << "pos=" << this->cursor.position();
}

But the position doesn't change anymore, as if it was fixed. So, is there a way to somehow update the cursor ? Or is the cost of repeated creation of a QTextCursor insignificant ?

update : writing something like...

mycursor= this->cursorForPosition(mouse_event->pos());

... creates a new cursor and seems to be the equivalent to :

mycursor= this->textCursor();
1

There are 1 best solutions below

0
On

In your first example, instead of

    mycursor = this->textCursor();
    qDebug() << "pos=" << mycursor.position();

why do not you call it directly as?

    qDebug() << "pos=" << this->textCursor().position();

Because in python

    self.textCursor().position() 

works.

Also, I am not sure but in your second example maybe you need to set the "cursor" as "textCursor" again with setTextCursor().

    void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
           this->setTextCursor(cursor)
           qDebug() << "pos=" << this->cursor.position();
    }