Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain Syntax Highlighting during text highlight

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);
}
like image 909
Griffort Avatar asked Feb 13 '18 00:02

Griffort


People also ask

How do I change the highlighting syntax?

You can specify the default syntax highlighting type for new files in Settings » Editor Display » Syntax Highlighting. You can add or remove wordfiles for syntax highlighting by clicking the Add another language... button in the Formatting group of the Coding tab.

How do I enable syntax highlighting in Notepad ++?

Open Notepad++ once again, go back to the language menu, and at the bottom between "Define your language" and "User-Defined" you should find "choicescript". Select it and and your code should automatically be highlighted.

Does markdown support highlighting?

By default, markdown does not support text highlight content. There are multiple ways we can do it using HTML.


1 Answers

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! ~

like image 183
Griffort Avatar answered Sep 19 '22 03:09

Griffort