23

我正在使用QPlainTextEditand制作自定义代码编辑器,QSyntaxHighlighter但遇到了一个小故障。即使在选择中,我也想保留语法突出显示。但是,选择的颜色(环境颜色)会覆盖由QSyntaxHighlighterhtml 标记突出显示的文本的颜色。字体系列等其他属性被保留。


例子:

无选择: 选择:(                                    我要绿色和黑色)
未选中      已选中
HelloWorld!


我还尝试将样式表设置为:

QPlainTextEdit {
    selection-color: rgba(0, 0, 0, 0);
    selection-background-color: lightblue;
}

结果:

在此处输入图像描述
背景颜色覆盖了文本,并且文本颜色alpha = 0不可见。我这样做只是为了排除语法颜色在selection-color. 它实际上被 覆盖selection-background-color
编辑:不,如果我也设置selection-background-colorrgba(0, 0, 0, 0),则没有选择,并且该选择中没有文本。我看到的只是背景。


以下片段的方法使整个光标的行突出显示似乎是要走的路,但我基本上最终会重新实现所有选择机制......

QList<QTextEdit::ExtraSelection> extraSelections;
QTextCursor cursor = textCursor();

QTextEdit::ExtraSelection selection;
selection.format.setBackground(lineHighlightColor_);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = cursor;
selection.cursor.clearSelection();
extraSelections.append(selection);
setExtraSelections(extraSelections);

有没有更简单的解决方案?

4

1 回答 1

5

问题出在这里:

https://github.com/qt/qtbase/blob/e03b64c5b1eeebfbbb94d67eb9a9c1d35eaba0bb/src/widgets/widgets/qplaintextedit.cpp#L1939-L1945

QPlainTextEdit 使用上下文调色板而不是当前选择格式。

您可以从 QPlainTextEdit 创建一个类继承并覆盖paintEvent

签名 :

void paintEvent(QPaintEvent *);

从新类paintEvent函数中的github复制函数体:

https://github.com/qt/qtbase/blob/e03b64c5b1eeebfbbb94d67eb9a9c1d35eaba0bb/src/widgets/widgets/qplaintextedit.cpp#L1883-L2013

在paintEvent之前在你的cpp文件中添加这个函数(PlainTextEdit paintEvent需要它):

https://github.com/qt/qtbase/blob/e03b64c5b1eeebfbbb94d67eb9a9c1d35eaba0bb/src/widgets/widgets/qplaintextedit.cpp#L1861-L1876

添加

#include <QPainter>
#include <QTextBlock>
#include <QScrollBar>

并替换每次出现

o.format = range.format;

哪里

o.format = range.cursor.blockCharFormat();
o.format.setBackground(QColor(your selection color with alpha));

使用您的自定义 PlainTextEdit 检查链接到当前字符而不是您的 PlainTextEdit 调色板的格式

(注意(L)GPL 许可证,我只是给出一个开源解决方法)

于 2017-10-11T13:22:34.337 回答