Important: Please read the Qt Code of Conduct -

QGraphicsTextItem cursor issue when setting new text

  • Hey.
    I have subclassed QGraphicsTextItem so that I can perform some validation on the input, and I'm having some issues with the cursor.
    Here's a code snippet of how my class looks like:

    class TextItem(QGraphicsTextItem):
    	def __init__(self, parent = None):
    		super(TextItem, self).__init__(parent)
    	def keyPressEvent(self, event):
    		if event.key() == Qt.Key_Return or event.key() == Qt.Key_Escape:
    		cursor = self.textCursor() # this, according to the doc, returns a *copy* of the cursor
    		# TODO: perform some validation on event.key()
    		self.setHtml('validated text') # this changes the cursor, setting it to the end of the line!
    		self.setTextCursor(cursor) # this has no effect

    As you can see from the comments, for some reason the self.setHtml() invocation changes the cursor, which is fine, as long as I can set it back, but that's the problem - self.setTextCursor(cursor) has no effect!
    Can someone please shed some light on what is going on here?


    [Edit: moved to Language Bindings ~~ @Wieland]

  • Hi @ChainReaction

    When the cursor is at the end of the line and you move it to the "next character", it stays put at the end. I would try QTextCursor::StartOfLine.


  • Hey @m-sue , thanks for your reply.

    1. The problem isn't that cursor.movePosition(QTextCursor.NextCharacter) does not move the cursor, but rather that self.setHtml() sends the cursor to the end regardless of its current position.
    2. This does not explain why self.setTextCursor(cursor) has no effect.

Log in to reply