2015-01-31 143 views
19

我正在做一個自定義代碼編輯器QPlainTextEditQSyntaxHighlighter,我遇到了一個小故障。我想要在選擇中保留語法高亮。但是,選擇(環境顏色)的顏色會覆蓋由QSyntaxHighlighter和html標記突出顯示的文本的顏色。保留了其他屬性,如字體系列。QSyntaxHighlighter - 文本選擇覆蓋樣式


實施例:

無選擇:                     選擇:
Unselected         Selected
                                                                     (我想Hello是綠色和World!是黑色)


我也試圖設置樣式表:

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

結果:

enter image description here
背景顏色覆蓋文字和文字顏色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); 

有沒有更簡單解決這個問題?

+0

你有沒有找到一個簡單的解決方案? – 2016-05-08 14:25:44

+1

@NicolasHolthaus我已經辭職了。如果我找到了一個更簡單的方法(我不知道QTextEdit :: ExtraSelection是否是一個可行的解決方案),我會分享它。 – LogicStuff 2016-05-08 16:03:03

+3

這是一個令人討厭的語法熒光筆限制。 – 2016-05-08 16:20:12

回答

2

問題所在位置:

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

QPlainTextEdit使用上下文的調色板代替當前選擇格式。

你可以從你QPlainTextEdit創建一個類inheritings並重寫的paintEvent

簽名:

void paintEvent(QPaintEvent *); 

複製從類新的paintEvent函數內部GitHub上的函數體:

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

在paintEvent(PlainTextEdit paintEvent需要它)之前在你的cpp文件中添加這個函數:

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

添加

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

,並與您的自定義PlainTextEdit檢查日更換的

o.format = range.format; 

每次出現蒙山

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

Ë格式鏈接到當前字符,而不是你的PlainTextEdit調色板

(當心(L)GPL許可,我只給一個開源的解決方法)