使用QTextCharFormat更改选择颜色

时间:2014-04-13 13:42:32

标签: pyqt pyside qtextedit

我正在编写简单的编辑器,我使用QTextEdit进行文本编辑QSyntaxHighlighter进行语法着色。 样式由QTextCharFormat提供。

我知道如何创建简单的样式:

keyword_format = QtGui.QTextCharFormat()
keyword_format.setForeground(QtCore.Qt.darkMagenta)
keyword_format.setFontWeight(QtGui.QFont.Bold)

exception_format = QtGui.QTextCharFormat()
exception_format.setForeground(QtCore.Qt.darkBlue)
exception_format.setFontWeight(QtGui.QFont.Italic)

但是如何在选择文本时更改颜色并且:
1.所选文本可能包含许多不同格式的标记
2.我可能想要为每个格式化程序单独设置选择背景颜色和字体颜色

我不知道我是否清楚地解释了它,例如我有代码

 if foobar:
     return foobar:
 else:
     raise Exception('foobar not set')

现在,ifelsereturnraise是关键字,使用keyword_format格式化,Exception使用{{格式化1}}。如果我选择文字exception_format,我想将raise Exception('foobar not set')关键字更改为绿色,将raise更改为粉红色并保留其余选择。

如何实现?感谢。

1 个答案:

答案 0 :(得分:0)

您可以将mergeCharFormat()与QTextCursor结合使用,指向QTextEdit内部的document()

用法(C ++):

true

即使在合并第二个QTextCharFormat之前移动了光标,它似乎仍然可以工作

相关问题