5

In most code editors, the text highlight does not remove the syntax colors.

For example:

  • Visual Studio

example Visual Studio

  • Sublime Text

example Sublime Text

I would like to simulate this function in the code editor I'm making in QT; however, the text highlight turns all of the text into a single color:

dsd vs dsad

Would it be possible to retain the syntax highlighting during a text highlight?


FYI: I'm using a QPlainTextEdit and QSyntaxHighlighter to create the editor. I've tried changing the palette of the QPlainTextEdit, but I cannot seem to find a way to disable the HighlightedText effect.


EDIT: Here is a simplified version of the code I'm using to add some context:

void MyHighlighter::highlightBlock(const QString& text) {
  // Sets characters 0 ~ 10 to be colored rgb(100, 200, 100)
  QTextCharFormat temp;
  temp.setForeground(QColor(100, 200, 100));
  setFormat(0, 10, temp);
}
Griffort
  • 1,174
  • 1
  • 10
  • 26
  • 1
    show more code, how do you define style. I'm sure you can define different style of text when it is selected and you simply missed that. – Marek R Feb 13 '18 at 00:20
  • @MarekR I'm simply using the `setFormat` function within an extended `QSyntaxHighlighter::highlightBlock`. I've added a small example to the original post. I've tried looking for something to modify the `QTextCharFormat` to make the highlight color the same, but no luck. (Also, thanks for the post edit. Was unaware you could embed images like that >.<) – Griffort Feb 13 '18 at 00:43
  • I've checked how Qt Creator works. Sadly it has this issue, that selected text is in not colored. So it might be hard to do what you want. – Marek R Feb 14 '18 at 19:02
  • @MarekR Ack, I see. Is there a specific place in the code I should look to find where the text re-color is done? Perhaps I could figure it out from there. – Griffort Feb 14 '18 at 19:53

1 Answers1

6

Good news! After revisiting this issue, I found the solution after playing around for a bit. Feel a little stupid not trying this sooner as it works perfectly.

On the QPlainTextEdit (or whichever widget applicable to the scenario), you simply need to set the QPalette::HighlightedText to QBrush(Qt::NoBrush).


For example, to replicate the transparent highlight from Sublime Text, you would simply do:

auto palette = textEditWidget->palette();

// provide highlight color with low alpha
palette.setBrush(QPalette::Highlight, QColor(255, 255, 255, 30));

// set highlight text brush to "No Brush"
palette.setBrush(QPalette::HighlightedText, QBrush(Qt::NoBrush));

// apply to widget
textEditWidget->setPalette(palette);

Result:

i did the thing. hurrah! ~

Griffort
  • 1,174
  • 1
  • 10
  • 26