Search code examples
pythoncursorpyqt4

SetTextCursor in PyQt4


Every time textChanged() is emitted, the text of QTextBrowser is processed and then re-inserted in that QTextBrowser. That causes trouble with the current Cursor.

How do I do that after typing something at | and re-inserting the text, the cursor is behind the newly inserted character (here: X) ?

Hello| World

Where it should be:

HelloX| World

Where it is:

|HelloX World

I need some help because I don't understand the according part of the QT documentation.


Solution

  • If you're inserting text after the cursor, as yor example suggests, you, you should use the text cursor's insertText method instead of replacing the whole content of the editor - should save you some trouble:

    editor.textCursor().insertText('X')
    

    Otherwise you should be able to restore the previous position like this:

    old_position = editor.textCursor().position()
    # ...
    new_cursor = editor.textCursor()
    new_cursor.setPosition(old_position)
    editor.setTextCursor(cursor)