【问题标题】:QSyntaxHighlighter - text selection overrides styleQSyntaxHighlighter - 文本选择覆盖样式
【发布时间】:2015-03-31 04:13:40
【问题描述】:

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


示例:

没有选择:            选择:
    
(我希望 Hello 为绿色,World! 为黑色)


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

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

结果:


背景颜色覆盖了文本,并且alpha = 0 的文本颜色不可见。我这样做只是为了排除语法颜色在selection-color 下仍然存在的想法。它实际上被selection-background-color 覆盖。
编辑:不,如果我还将selection-background-color 设置为rgba(0, 0, 0, 0),则没有选择,并且该选择中没有文本。我看到的只是背景。


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

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);

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

【问题讨论】:

  • 你有没有找到更简单的解决方案?
  • @NicolasHolthaus 我已经辞职了。如果我找到了一种更简单的方法(我不知道QTextEdit::ExtraSelection 是否是一个可行的解决方案),我会分享它。
  • 这是语法高亮的一个非常烦人的限制。

标签: qt qt5 qtstylesheets qplaintextedit


【解决方案1】:

问题出在这里:

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

在你的cpp文件中在paintEvent之前添加这个函数(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 许可证,我只是提供了一个开源解决方法)

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2020-06-15
    相关资源
    最近更新 更多