Please nominate your Qt Champions for 2021!

Problem with QTextCursor selection

  • Hi,

    I'm have a situation where I need to customize the input to a QGraphicsTextItem. In particular, I need to select characters in response to an up-arrow key press. So I have created a custom QGraphicsTextItem and over-ridden the keyPressEvent,

    @ class MyText : public QGraphicsTextItem
    MyText(const char* str) : QGraphicsTextItem(str)

      virtual void keyPressEvent(QKeyEvent* event)
        QTextCursor cursor = textCursor();
        if (event->key() == Qt::Key_Down)


    Through the testing I've done, this is selecting text (e.g. if I called removeSelectedText() the text is correctly removed). The problem is that I need to have the visual indicator of the selection and I do not see it for some reason. Am I doing something wrong, or does the selection performed by QTextCursor not get displayed graphically?


  • You have to set the cursor back onto the text edit once you move its position.

    cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);

  • I don't think that is quite right. setCursor() defines the mouse cursor via QCursor, I am modifying text with QTextCursor, which does not inherit from QCursor so I cannot pass it to setCursor().

  • ok you got me, setTextCursor is the the call. textCursor returns a copy of the QTextCursor, thats why you have to set it back into the object.

  • Arg, of course! Thank you for the help, that seems to have fixed the problem.

Log in to reply