Search code examples
pythonpyqtqtextedit

In PyQt QTextEdit.setTextColor() doesn't work before moving cursor


Setting the QTextEdit color with the setTextColor method doesn't have effect if done after the moveCursor method.

terminal = QTextEdit()
terminal.setTextColor(color)
terminal.moveCursor(QTextCursor.End)
terminal.insertPlainText('Test\n')

But if the cursor is moved before setting the color, it works.

terminal = QTextEdit()
terminal.moveCursor(QTextCursor.End)
terminal.setTextColor(color)
terminal.insertPlainText('Test\n')

Why does this happen? The documentation doesn't seem to have anything about this behavior.


Solution

  • What is most likely happening is the call to setTextColor is inserting something invisible into your document that changes the color. Perhaps it is adding an opening and a closing tag that specify a colored region of text and putting your cursor in the middle of these tags. When you call moveCursor and jump to the end you are jumping out of this colored region and your color stops working.

    The second example works because you do not move out off the colored region.