在 PyQt 中 QTextEdit.setTextColor() 在移动光标之前不起作用
In PyQt QTextEdit.setTextColor() doesn't work before moving cursor
如果在 moveCursor 方法之后完成,使用 setTextColor 方法设置 QTextEdit 颜色不会生效。
terminal = QTextEdit()
terminal.setTextColor(color)
terminal.moveCursor(QTextCursor.End)
terminal.insertPlainText('Test\n')
但是如果在设置颜色之前移动光标,它会起作用。
terminal = QTextEdit()
terminal.moveCursor(QTextCursor.End)
terminal.setTextColor(color)
terminal.insertPlainText('Test\n')
为什么会这样? documentation 似乎没有关于此行为的任何信息。
最有可能发生的情况是调用 setTextColor 时会在您的文档中插入不可见的内容以更改颜色。也许它正在添加一个开始和结束标记,指定文本的彩色区域并将光标放在这些标记的中间。当您调用 moveCursor 并跳到最后时,您将跳出这个彩色区域并且您的颜色将停止工作。
第二个示例有效,因为您没有移出彩色区域。
如果在 moveCursor 方法之后完成,使用 setTextColor 方法设置 QTextEdit 颜色不会生效。
terminal = QTextEdit()
terminal.setTextColor(color)
terminal.moveCursor(QTextCursor.End)
terminal.insertPlainText('Test\n')
但是如果在设置颜色之前移动光标,它会起作用。
terminal = QTextEdit()
terminal.moveCursor(QTextCursor.End)
terminal.setTextColor(color)
terminal.insertPlainText('Test\n')
为什么会这样? documentation 似乎没有关于此行为的任何信息。
最有可能发生的情况是调用 setTextColor 时会在您的文档中插入不可见的内容以更改颜色。也许它正在添加一个开始和结束标记,指定文本的彩色区域并将光标放在这些标记的中间。当您调用 moveCursor 并跳到最后时,您将跳出这个彩色区域并且您的颜色将停止工作。
第二个示例有效,因为您没有移出彩色区域。