使用 QTextCharFormat 更改选择颜色

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)

但是当选择文本时如何改变颜色并且:

  1. 所选文本可能包含许多不同格式的标记
  2. 我可能想为每个格式化程序独立设置选择背景颜色和字体颜色

我不知道我是否解释得足够清楚,例如我有代码

 if foobar:
     return foobar:
 else:
     raise Exception('foobar not set')
Run Code Online (Sandbox Code Playgroud)

现在,ifelsereturnraise是关键字,并使用 进行格式化keyword_formatException使用 进行格式化exception_format。如果我选择文本,raise Exception('foobar not set')我想更改raise关键字,例如绿色、Exception粉色,并保留其余选择不变。

Aka*_*sha 1

您可以将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 之前移动光标,它似乎也能工作