QSyntaxHighlighter

Inheritance diagram of QSyntaxHighlighter

Synopsis

Functions

Virtual functions

Slots

Detailed Description

The PySide.QtGui.QSyntaxHighlighter class allows you to define syntax highlighting rules, and in addition you can use the class to query a document’s current formatting or user data.

The PySide.QtGui.QSyntaxHighlighter class is a base class for implementing PySide.QtGui.QTextEdit syntax highlighters. A syntax highligher automatically highlights parts of the text in a PySide.QtGui.QTextEdit , or more generally in a PySide.QtGui.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 PySide.QtGui.QSyntaxHighlighter and reimplement PySide.QtGui.QSyntaxHighlighter.highlightBlock() .

When you create an instance of your PySide.QtGui.QSyntaxHighlighter subclass, pass it the PySide.QtGui.QTextEdit or PySide.QtGui.QTextDocument that you want the syntax highlighting to be applied to. For example:

editor = QTextEdit()
highlighter = MyHighlighter(editor.document())

After this your PySide.QtGui.QSyntaxHighlighter.highlightBlock() function will be called automatically whenever necessary. Use your PySide.QtGui.QSyntaxHighlighter.highlightBlock() function to apply formatting (e.g. setting the font and color) to the text that is passed to it. PySide.QtGui.QSyntaxHighlighter provides the PySide.QtGui.QSyntaxHighlighter.setFormat() function which applies a given PySide.QtGui.QTextCharFormat on the current text block. For example:

class MyHighlighter(QSyntaxHighlighter):
    def highlightBlock(self, text):
        myClassFormat = QTextCharFormat()
        myClassFormat.setFontWeight(QFont.Bold)
        myClassFormat.setForeground(Qt.darkMagenta)
        pattern = QString("\\bMy[A-Za-z]+\\b")

        expression = QRegExp(pattern)
        index = text.indexOf(expression)
        while index >= 0:
            length = expression.matchedLength()
            setFormat(index, length, myClassFormat)
            index = text.indexOf(expression, index + length)

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 PySide.QtGui.QSyntaxHighlighter.highlightBlock() implementation you can query the end state of the previous text block using the PySide.QtGui.QSyntaxHighlighter.previousBlockState() function. After parsing the block you can save the last state using PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState() .

The PySide.QtGui.QSyntaxHighlighter.currentBlockState() and PySide.QtGui.QSyntaxHighlighter.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 PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState() function. Once the state is set the PySide.QtGui.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”:

multiLineCommentFormat = QTextCharFormat()
multiLineCommentFormat.setForeground(Qt.red)

startExpression = QRegExp("/\\*")
endExpression = QRegExp("\\*/")

setCurrentBlockState(0)

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

while startIndex >= 0:
    endIndex = text.indexOf(endExpression, startIndex)
    if endIndex == -1:
       setCurrentBlockState(1)
       commentLength = text.length() - startIndex
    else:
       commentLength = endIndex - startIndex
                       + endExpression.matchedLength()

    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 higlight 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 PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState() , and make sure that the rest of the block is higlighted.

In addition you can query the current formatting and user data using the PySide.QtGui.QSyntaxHighlighter.format() and PySide.QtGui.QSyntaxHighlighter.currentBlockUserData() functions respectively. You can also attach user data to the current text block using the PySide.QtGui.QSyntaxHighlighter.setCurrentBlockUserData() function. PySide.QtGui.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 PySide.QtGui.QSyntaxHighlighter.setCurrentBlockUserData() documentation.

See also

PySide.QtGui.QTextEdit Syntax Highlighter Example

class PySide.QtGui.QSyntaxHighlighter(parent)
class PySide.QtGui.QSyntaxHighlighter(parent)
class PySide.QtGui.QSyntaxHighlighter(parent)
Parameters:parentPySide.QtCore.QObject

Constructs a PySide.QtGui.QSyntaxHighlighter with the given parent .

Constructs a PySide.QtGui.QSyntaxHighlighter and installs it on parent . The specified PySide.QtGui.QTextDocument also becomes the owner of the PySide.QtGui.QSyntaxHighlighter .

Constructs a PySide.QtGui.QSyntaxHighlighter and installs it on parent ‘s PySide.QtGui.QTextDocument . The specified PySide.QtGui.QTextEdit also becomes the owner of the PySide.QtGui.QSyntaxHighlighter .

PySide.QtGui.QSyntaxHighlighter.currentBlock()
Return type:PySide.QtGui.QTextBlock

Returns the current text block.

PySide.QtGui.QSyntaxHighlighter.currentBlockState()
Return type:PySide.QtCore.int

Returns the state of the current text block. If no value is set, the returned value is -1.

PySide.QtGui.QSyntaxHighlighter.currentBlockUserData()
Return type:PySide.QtGui.QTextBlockUserData

Returns the PySide.QtGui.QTextBlockUserData object previously attached to the current text block.

PySide.QtGui.QSyntaxHighlighter.document()
Return type:PySide.QtGui.QTextDocument

Returns the PySide.QtGui.QTextDocument on which this syntax highlighter is installed.

PySide.QtGui.QSyntaxHighlighter.format(pos)
Parameters:posPySide.QtCore.int
Return type:PySide.QtGui.QTextCharFormat

Returns the format at position inside the syntax highlighter’s current text block.

PySide.QtGui.QSyntaxHighlighter.highlightBlock(text)
Parameters:text – unicode

Highlights the given text block. This function is called when necessary by the rich text engine, i.e. on text blocks which have changed.

To provide your own syntax highlighting, you must subclass PySide.QtGui.QSyntaxHighlighter and reimplement PySide.QtGui.QSyntaxHighlighter.highlightBlock() . In your reimplementation you should parse the block’s text and call PySide.QtGui.QSyntaxHighlighter.setFormat() as often as necessary to apply any font and color changes that you require. For example:

class MyHighlighter(QSyntaxHighlighter):
    def highlightBlock(self, text):
        myClassFormat = QTextCharFormat()
        myClassFormat.setFontWeight(QFont.Bold)
        myClassFormat.setForeground(Qt.darkMagenta)
        pattern = QString("\\bMy[A-Za-z]+\\b")

        expression = QRegExp(pattern)
        index = text.indexOf(expression)
        while index >= 0:
            length = expression.matchedLength()
            setFormat(index, length, myClassFormat)
            index = text.indexOf(expression, index + length)

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 PySide.QtGui.QSyntaxHighlighter.highlightBlock() implementation you can query the end state of the previous text block using the PySide.QtGui.QSyntaxHighlighter.previousBlockState() function. After parsing the block you can save the last state using PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState() .

The PySide.QtGui.QSyntaxHighlighter.currentBlockState() and PySide.QtGui.QSyntaxHighlighter.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 PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState() function. Once the state is set the PySide.QtGui.QTextBlock keeps that value until it is set set again or until the corresponding paragraph of text gets deleted.

For example, if you’re writing a simple C++ syntax highlighter, you might designate 1 to signify “in comment”. For a text block that ended in the middle of a comment you’d set 1 using setCurrentBlockState, and for other paragraphs you’d set 0. In your parsing code if the return value of PySide.QtGui.QSyntaxHighlighter.previousBlockState() is 1, you would highlight the text as a C++ comment until you reached the closing */ .

PySide.QtGui.QSyntaxHighlighter.previousBlockState()
Return type:PySide.QtCore.int

Returns the end state of the text block previous to the syntax highlighter’s current block. If no value was previously set, the returned value is -1.

PySide.QtGui.QSyntaxHighlighter.rehighlight()

Reapplies the highlighting to the whole document.

PySide.QtGui.QSyntaxHighlighter.rehighlightBlock(block)
Parameters:blockPySide.QtGui.QTextBlock

Reapplies the highlighting to the given PySide.QtGui.QTextBlock block .

PySide.QtGui.QSyntaxHighlighter.setCurrentBlockState(newState)
Parameters:newStatePySide.QtCore.int

Sets the state of the current text block to newState .

PySide.QtGui.QSyntaxHighlighter.setCurrentBlockUserData(data)
Parameters:dataPySide.QtGui.QTextBlockUserData

Attaches the given data to the current text block. The ownership is passed to the underlying text document, i.e. the provided PySide.QtGui.QTextBlockUserData object will be deleted if the corresponding text block gets deleted.

PySide.QtGui.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 example while parsing the text, you can keep track of parenthesis characters that you encounter (‘{[(‘ and the like), and store their relative position and the actual PySide.QtCore.QChar in a simple class derived from PySide.QtGui.QTextBlockUserData :

class BlockData(QTextBlockUserData):
    def __init__(self):
        # ...
        self.parentheses = []

During cursor navigation in the associated editor, you can ask the current PySide.QtGui.QTextBlock (retrieved using the QTextCursor.block() function) if it has a user data object set and cast it to your BlockData object. Then you can check if the current cursor position matches with a previously recorded parenthesis position, and, depending on the type of parenthesis (opening or closing), find the next opening or closing parenthesis on the same level.

In this way you can do a visual parenthesis matching and highlight from the current cursor position to the matching parenthesis. That makes it easier to spot a missing parenthesis in your code and to find where a corresponding opening/closing parenthesis is when editing parenthesis intensive code.

PySide.QtGui.QSyntaxHighlighter.setDocument(doc)
Parameters:docPySide.QtGui.QTextDocument

Installs the syntax highlighter on the given PySide.QtGui.QTextDocument doc . A PySide.QtGui.QSyntaxHighlighter can only be used with one document at a time.

PySide.QtGui.QSyntaxHighlighter.setFormat(start, count, font)
Parameters:

This is an overloaded function.

The specified font is applied to the current text block from the start position for a length of count characters.

The other attributes of the current text block, e.g. the font and background color, are reset to default values.

PySide.QtGui.QSyntaxHighlighter.setFormat(start, count, color)
Parameters:

This is an overloaded function.

The specified color is applied to the current text block from the start position for a length of count characters.

The other attributes of the current text block, e.g. the font and background color, are reset to default values.

PySide.QtGui.QSyntaxHighlighter.setFormat(start, count, format)
Parameters:

This function is applied to the syntax highlighter’s current text block (i.e. the text that is passed to the PySide.QtGui.QSyntaxHighlighter.highlightBlock() function).

The specified format is applied to the text from the start position for a length of count characters (if count is 0, nothing is done). The formatting properties set in format are merged at display time with the formatting information stored directly in the document, for example as previously set with PySide.QtGui.QTextCursor ‘s functions. Note that the document itself remains unmodified by the format set through this function.