[Solved] Want to turn syntax highlighting on and off - how?
-
I have implemented a simple syntax highlighter on a QPlainTextEdit, and it works, BUT:
The user wants to turn highlighting on or off. I provided a View menu with a checkable action Highlight; it sets a global switch true/false. My highlightBlock function tests this switch and does nothing if it is false.
Alas, the QTextDocument is too clever by half! It seems to call highlightBlock once for every bit of the document when the document is first loaded (which I do with self.setPlainText(dataStream.readAll()) ). Thereafter it never calls highlightBlock again, except to see the smallest span of text that has been edited. Very efficient, but the result is,
-
If the global switch is False when the document is loaded, no highlighting appears (as expected), but when the user selects View>Highlight, STILL no highlighting appears, except on the least span of new or altered text just where the user is typing.
-
If the global switch is True when the document is loaded, all highlighting appears everywhere (as expected), but if the user then toggles View>Highlight off, all the highlighting REMAINS and only goes away on the spans of text that are edited. In hindsight this is not wrong, as all the QTextFormats inserted by highlightBlock remain in place.
So: two questions. One, how can I make the TextDocument re-apply highlightBlock() to all text, when the user says "begin to highlight" on an existing document?
And Two, when the user says "ok, stop highlighting," how can I clear out all the TextFormats that my highlighter put in, to make them disappear?
-
-
Instead of a button, I would use a [[Doc:QCheckBox]], that's more clear to the user. The rest is easy:
Add a new protected slot to your class:
@
protected slots:
void toggleHighlightOn(bool doHighlight);
@Add a checkbox to your UI and connect the signal to your slot:
@
connect(ui->checkBoxHighlighter, SIGNAL(toggled(bool)), this, SLOT(toggleHighlightOn(bool)));
@And just switch the [[Doc:QTextDocument]] in the highlighter object according to the checkbox:
@
void MainWindow::toggleHighlightOn(bool doHighlight)
{
highlighter->setDocument(doHighlight ? editor->document() : 0);
}
@The trick is to set the document pointer of the highlighter to null in order to switch off highlighting, and set it back to the text editor's document to re-highlight.
-
Awesome - that works beautifully. To stop highlighting and clear all highlights, I merely call highlighter.setDocument(a null textdocument).
To restore highlighting everywhere, I set its document back to the real document. Simple, clean, easy. Thank you!
-
Cheers - glad it helped you. I've added the snippet as note to the [[Doc:QSyntaxHighlighter]] docs.