Skip to content

PythonQt.Qt.QSyntaxHighlighter

QSyntaxHighlighter

PythonQtInstanceWrapper object

Native bases: PythonQtInstanceWrapper

Supplemental documentation: Qt 5 reference:

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->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 &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":

QTextCharFormat multiLineCommentFormat;
multiLineCommentFormat.setForeground(Qt::red);

QRegularExpression startExpression("/\\*");
QRegularExpression endExpression("\\*/");

setCurrentBlockState(0);

int startIndex = 0;
if (previousBlockState() != 1)
    startIndex = text.indexOf(startExpression);

while (startIndex >= 0) {
   QRegularExpressionMatch endMatch;
   int endIndex = text.indexOf(endExpression, startIndex, &endMatch);
   int commentLength;
   if (endIndex == -1) {
       setCurrentBlockState(1);
       commentLength = text.length() - startIndex;
   } else {
       commentLength = endIndex - startIndex
                       + endMatch.capturedLength();
   }
   setFormat(startIndex, commentLength, multiLineCommentFormat);
   startIndex = text.indexOf(startExpression,
                             startIndex + commentLength);
}

In the example above, we first set the current block state to 0. Then, if the previous block ended within a comment, we highlight from the beginning of the current block (startIndex = 0). Otherwise, we search for the given start expression. If the specified end expression cannot be found in the text block, we change the current block state by calling setCurrentBlockState(), and make sure that the rest of the block is highlighted.

In addition you can query the current formatting and user data using the format() and currentBlockUserData() functions respectively. You can also attach user data to the current text block using the setCurrentBlockUserData() function. QTextBlockUserData can be used to store custom settings. In the case of syntax highlighting, it is in particular interesting as cache storage for information that you may figure out while parsing the paragraph's text. For an example, see the setCurrentBlockUserData() documentation.

Source: https://doc.qt.io/archives/qt-5.15/qsyntaxhighlighter.html

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
__init__ function (self, *args: Any, **kwargs: Any) -> None Native constructor; consult class documentation for supported overloads. (shared captured text)
blockSignals function (self, b: Any) -> bool X.blockSignals(b) -> bool (shared captured text)
childEvent function (self, event: Any) -> Any (shared captured text)
children function (self) -> tuple X.children() -> tuple (shared captured text)
className function (self, *args: Any, **kwargs: Any) -> Any Return the classname of the object (shared captured text)
connect function (self, signal: Any, receiver: Any, slot: Any, type: Any) -> bool X.connect(signal, receiver, slot, type) -> bool (shared captured text)
currentBlock function (self) -> Any X.currentBlock() -> PythonQt.QtGui.QTextBlock (shared captured text)
currentBlockState function (self) -> int X.currentBlockState() -> int (shared captured text)
currentBlockUserData function (self) -> Any X.currentBlockUserData() -> PythonQt.QtGui.QTextBlockUserData (shared captured text)
customEvent function (self, event: Any) -> Any (shared captured text)
delete function (self, *args: Any, **kwargs: Any) -> Any Deletes the C++ object (at your own risk, my friend!) (shared captured text)
deleteLater function (self) -> Any (shared captured text)
destroyed function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QSyntaxHighlighter.destroyed; argument details are not documented.
disconnect function (self, signal: Any, receiver: Any, slot: Any) -> bool X.disconnect(signal, receiver, slot) -> bool (shared captured text)
document function (self) -> Any X.document() -> PythonQt.QtGui.QTextDocument (shared captured text)
dumpObjectInfo function (self) -> Any (shared captured text)
dumpObjectTree function (self) -> Any (shared captured text)
dynamicPropertyNames function (self) -> Any (shared captured text)
event function (self, event: Any) -> bool X.event(event) -> bool (shared captured text)
eventFilter function (self, watched: Any, event: Any) -> bool X.eventFilter(watched, event) -> bool (shared captured text)
findChild function (self, type: Any, name: Any) -> Any X.findChild(type, name) -> PythonQt.private.QObject (shared captured text)
findChildren function (self, type: Any, name: Any) -> tuple X.findChildren(type, name) -> tuple (shared captured text)
format function (self, pos: int) -> Any X.format(pos) -> PythonQt.QtGui.QTextCharFormat (shared captured text)
help function (self, *args: Any, **kwargs: Any) -> Any Shows the help of available methods for this class (shared captured text)
highlightBlock function (self, text: str) -> None Highlights the given text block. (shared captured text)
inherits function (self, *args: Any, **kwargs: Any) -> Any Returns if the class inherits or is of given type name (shared captured text)
installEventFilter function (self, filterObj: Any) -> Any (shared captured text)
isSignalConnected function (self, signal: Any) -> bool X.isSignalConnected(signal) -> bool (shared captured text)
isWidgetType function (self) -> bool X.isWidgetType() -> bool (shared captured text)
isWindowType function (self) -> bool X.isWindowType() -> bool (shared captured text)
killTimer function (self, id: Any) -> Any (shared captured text)
metaObject function (self) -> Any X.metaObject() -> PythonQt.QtCore.QMetaObject (shared captured text)
moveToThread function (self, thread: Any) -> Any (shared captured text)
objectName attribute Any (shared captured text)
objectNameChanged function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QSyntaxHighlighter.objectNameChanged; argument details are not documented.
parent function (self) -> Any X.parent() -> PythonQt.private.QObject (shared captured text)
previousBlockState function (self) -> int X.previousBlockState() -> int (shared captured text)
property function (self, name: Any) -> Any X.property(name) -> object (shared captured text)
rehighlight function (self) -> None Reapplies the highlighting to the whole document. (shared captured text)
rehighlightBlock function (self, block: Any) -> None Reapplies the highlighting to the given [QTextBlock](https://doc.qt.io/archives/qt-5.15/qtextblock.html) block. (shared captured text)
removeEventFilter function (self, obj: Any) -> Any (shared captured text)
sender function (self) -> Any X.sender() -> PythonQt.private.QObject (shared captured text)
senderSignalIndex function (self) -> int X.senderSignalIndex() -> int (shared captured text)
setCurrentBlockState function (self, newState: int) -> None Sets the state of the current text block to newState. (shared captured text)
setCurrentBlockUserData function (self, data: Any) -> None Attaches the given data to the current text block. (shared captured text)
setDocument function (self, doc: Any) -> None Installs the syntax highlighter on the given [QTextDocument](https://doc.qt.io/archives/qt-5.15/qtextdocument.html) doc. (shared captured text)
setFormat function (self, start: int, count: int, color: Any) -> None X.setFormat(start, count, color) (shared captured text)
setObjectName function (self, name: Any) -> Any (shared captured text)
setParent function (self, parent: Any) -> Any (shared captured text)
setProperty function (self, name: Any, value: Any) -> bool X.setProperty(name, value) -> bool (shared captured text)
signalsBlocked function (self) -> bool X.signalsBlocked() -> bool (shared captured text)
startTimer function (self, interval: Any, timerType: Any) -> int X.startTimer(interval, timerType) -> int (shared captured text)
thread function (self) -> Any (shared captured text)
timerEvent function (self, event: Any) -> Any (shared captured text)
tr function (self, text: Any, ambig: Any, n: Any) -> str X.tr(text, ambig, n) -> str (shared captured text)