QSyntaxHighlighter Class▲
-
Header: QSyntaxHighlighter
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Gui)
target_link_libraries(mytarget PRIVATE Qt6::Gui)
-
qmake: QT += gui
-
Inherits: QObject
-
Group: QSyntaxHighlighter is part of Rich Text Processing APIs
Detailed Description▲
The QSyntaxHighlighter class is a base class for implementing QTextDocument syntax highlighters. A syntax highligher automatically highlights parts of the text in a QTextDocument. Syntax highlighters are often used when the user is entering text in a specific format (for example source code) and help the user to read the text and identify syntax errors.
To provide your own syntax highlighting, you must subclass QSyntaxHighlighter and reimplement highlightBlock().
When you create an instance of your QSyntaxHighlighter subclass, pass it the QTextDocument that you want the syntax highlighting to be applied to. For example:
QTextEdit *
editor =
new
QTextEdit;
MyHighlighter *
highlighter =
new
MyHighlighter(editor-&
gt;document());
After this your highlightBlock() function will be called automatically whenever necessary. Use your highlightBlock() function to apply formatting (e.g. setting the font and color) to the text that is passed to it. QSyntaxHighlighter provides the setFormat() function which applies a given QTextCharFormat on the current text block. For example:
void
MyHighlighter::
highlightBlock(const
QString &
amp;text)
{
QTextCharFormat myClassFormat;
myClassFormat.setFontWeight(QFont::
Bold);
myClassFormat.setForeground(Qt::
darkMagenta);
QRegularExpression expression("
\\
bMy[A-Za-z]+
\\
b"
);
QRegularExpressionMatchIterator i =
expression.globalMatch(text);
while
(i.hasNext()) {
QRegularExpressionMatch match =
i.next();
setFormat(match.capturedStart(), match.capturedLength(), myClassFormat);
}
}
Some syntaxes can have constructs that span several text blocks. For example, a C++ syntax highlighter should be able to cope with /*...*/ multiline comments. To deal with these cases it is necessary to know the end state of the previous text block (e.g. "in comment").
Inside your highlightBlock() implementation you can query the end state of the previous text block using the previousBlockState() function. After parsing the block you can save the last state using setCurrentBlockState().
The currentBlockState() and previousBlockState() functions return an int value. If no state is set, the returned value is -1. You can designate any other value to identify any given state using the setCurrentBlockState() function. Once the state is set the QTextBlock keeps that value until it is set set again or until the corresponding paragraph of text is deleted.
For example, if you're writing a simple C++ syntax highlighter, you might designate 1 to signify "in comment":