使用QTextCharFormat更改选择颜色

5 投票
1 回答
2511 浏览
提问于 2025-04-18 02:35

我正在写一个简单的编辑器,使用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使用exception_format来格式化。如果我选中这段文本raise Exception('foobar not set'),我希望把raise这个关键字的颜色改成绿色,把Exception改成粉色,其他的部分保持不变。

1 个回答

1

你可以使用 mergeCharFormat() 方法,配合一个指向 QTextEdit 中文档的 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);

即使在合并第二个 QTextCharFormat 之前移动了光标,这个方法似乎也能正常工作。

撰写回答