Home · Overviews · Examples 

QSyntaxHighlighter Class Reference
[com.trolltech.qt.gui module]

The 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. More...

Inherits QObject.


Detailed Description

The 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 QSyntaxHighlighter class is a base class for implementing QTextEdit syntax highlighters. A syntax highligher automatically highlights parts of the text in a QTextEdit, or more generally 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 QTextEdit or 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);
        QString pattern = "\\bMy[A-Za-z]+\\b";

        QRegExp expression(pattern);
        int index = text.indexOf(expression);
        while (index >= 0) {
            int 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 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);

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

    setCurrentBlockState(0);

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

    while (startIndex >= 0) {
       int endIndex = text.indexOf(endExpression, startIndex);
       int commentLength;
       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 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 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.

See also QTextEdit and Syntax Highlighter Example.


Copyright © 2008 Trolltech Trademarks
Qt Jambi 4.3.4_01