QSyntaxHighlighter - 文本选择覆盖样式

Log*_*uff 21 qt qplaintextedit qt5 qtstylesheets

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


例:

没有选择:选择:
未选择      选
                                   (我想Hello变成绿色,World!变成黑色)


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

QPlainTextEdit {
    selection-color: rgba(0, 0, 0, 0);
    selection-background-color: lightblue;
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述
背景颜色覆盖文本,并且文本颜色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);
Run Code Online (Sandbox Code Playgroud)

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

Bas*_*nat 5

问题出在这里:

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

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

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

签名 :

void paintEvent(QPaintEvent *);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

添加

#include <QPainter>
#include <QTextBlock>
#include <QScrollBar>
Run Code Online (Sandbox Code Playgroud)

并替换每次出现

o.format = range.format;
Run Code Online (Sandbox Code Playgroud)

蒙山

o.format = range.cursor.blockCharFormat();
o.format.setBackground(QColor(your selection color with alpha));
Run Code Online (Sandbox Code Playgroud)

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

(当心 (L)GPL 许可证,我只是提供了一个开源解决方法)