【问题标题】:Changing selection color using QTextCharFormat使用 QTextCharFormat 更改选择颜色
【发布时间】:2014-05-27 10:22:56
【问题描述】:

我正在编写简单的编辑器,我使用 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 更改为粉红色,其余选择保持不变。

【问题讨论】:

  • 我一直在尝试做类似的事情,即交换前景色和背景色。我认为几乎唯一的方法是检查/修改选择中的QTextFragments。您必须手动决定选择中的片段以及处理开始/结束片段的拆分。

标签: python pyqt pyside qtextedit


【解决方案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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2018-03-04
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多