ver*_*ule 5 python 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)
Run Code Online (Sandbox Code Playgroud)
但是当选择文本时如何改变颜色并且:
我不知道我是否解释得足够清楚,例如我有代码
if foobar:
return foobar:
else:
raise Exception('foobar not set')
Run Code Online (Sandbox Code Playgroud)
现在,if、else、return和raise是关键字,并使用 进行格式化keyword_format,Exception使用 进行格式化exception_format。如果我选择文本,raise Exception('foobar not set')我想更改raise关键字,例如绿色、Exception粉色,并保留其余选择不变。
您可以将mergeCharFormat()与指向 QTextEdit 内的 document() 的 QTextCursor 结合使用
用法(C++):
QTextCursor cursor(qTextEditWidget->document());
QTextCharFormat backgrounder;
backgrounder.setBackground(Qt::black);
QTextCharFormat foregrounder;
foregrounder.setForeground(Qt::yellow);
// Apply the background
cursor.setPosition(start, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
cursor.setCharFormat(backgrounder);
cursor.setPosition(start, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
// Merge the Foreground without overwriting the background
cursor.mergeCharFormat(foregrounder);
Run Code Online (Sandbox Code Playgroud)
即使在合并第二个 QTextCharFormat 之前移动光标,它似乎也能工作