QSyntaxHighlighter 类

QSyntaxHighlighter 类允许您定义句法高亮规则,此外,还可以使用该类查询文档的当前格式或用户数据。 更多...

头: #include <QSyntaxHighlighter>
CMake: find_package(Qt6 REQUIRED COMPONENTS Gui)
target_link_libraries(mytarget PRIVATE Qt6::Gui)
qmake: QT += gui
继承: QObject

注意: 此类的所有函数 可重入 .

公共函数

QSyntaxHighlighter (QObject * parent )
QSyntaxHighlighter (QTextDocument * parent )
virtual ~QSyntaxHighlighter ()
QTextDocument * document () const
void setDocument (QTextDocument * doc )

公共槽

void rehighlight ()
void rehighlightBlock (const QTextBlock & block )

保护函数

QTextBlock currentBlock () const
int currentBlockState () const
QTextBlockUserData * currentBlockUserData () const
QTextCharFormat format (int position ) const
virtual void highlightBlock (const QString & text ) = 0
int previousBlockState () const
void setCurrentBlockState (int newState )
void setCurrentBlockUserData (QTextBlockUserData * data )
void setFormat (int start , int count , const QTextCharFormat & format )
void setFormat (int start , int count , const QColor & color )
void setFormat (int start , int count , const QFont & font )

详细描述

QSyntaxHighlighter 类是基类,用于实现 QTextDocument 句法高亮器。句法高亮器会自动高亮部分文本在 QTextDocument 。经常使用句法高亮器,当用户以特定格式 (例如:源代码) 输入文本时,以帮助用户阅读文本和识别句法错误。

要提供您自己的句法高亮,必须子类化QSyntaxHighlighter 并重实现 highlightBlock ().

当创建 QSyntaxHighlighter 子类实例时,为其传递 QTextDocument ,希望应用句法高亮。例如:

QTextEdit *editor = new QTextEdit;
MyHighlighter *highlighter = new MyHighlighter(editor->document());
					

在此之后 highlightBlock () 函数会被自动调用 (每当必要时)。使用 highlightBlock () 函数以将格式化 (如:设置字体和颜色) 应用到被传递给它的文本。QSyntaxHighlighter 提供 setFormat () 函数应用给定 QTextCharFormat 在当前文本块。例如:

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 () 和 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 () 和 currentBlockUserData () functions respectively. You can also attach user data to the current text block using the setCurrentBlockUserData () 函数。 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 () 文档编制。

另请参阅 QTextDocument and 句法高亮范例 .

成员函数文档编制

[explicit] QSyntaxHighlighter:: QSyntaxHighlighter ( QObject * parent )

构造 QSyntaxHighlighter 采用给定 parent .

If the parent is a QTextEdit , it installs the syntax highlighter on the parents document. The specified QTextEdit 还会变为 QSyntaxHighlighter 的所有者。

[explicit] QSyntaxHighlighter:: QSyntaxHighlighter ( QTextDocument * parent )

构造 QSyntaxHighlighter 并将它安装在 parent 。指定 QTextDocument 还会变为 QSyntaxHighlighter 的所有者。

[虚拟] QSyntaxHighlighter:: ~QSyntaxHighlighter ()

Destructor. Uninstalls this syntax highlighter from the text document.

[protected] QTextBlock QSyntaxHighlighter:: currentBlock () const

返回当前文本块。

[protected] int QSyntaxHighlighter:: currentBlockState () const

返回当前文本块的状态。若值未设置,返回值为 -1。

另请参阅 setCurrentBlockState ().

[protected] QTextBlockUserData *QSyntaxHighlighter:: currentBlockUserData () const

返回 QTextBlockUserData 先前附加到当前文本块的对象。

另请参阅 QTextBlock::userData () 和 setCurrentBlockUserData ().

QTextDocument *QSyntaxHighlighter:: document () const

返回 QTextDocument 在其上有安装此句法高亮。

另请参阅 setDocument ().

[protected] QTextCharFormat QSyntaxHighlighter:: format ( int position ) const

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

另请参阅 setFormat ().

[pure virtual protected] void QSyntaxHighlighter:: highlightBlock (const QString & text )

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 QSyntaxHighlighter and reimplement highlightBlock(). In your reimplementation you should parse the block's text 和调用 setFormat () as often as necessary to apply any font and color changes that you require. 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);
    }
}
					

详细描述 for examples of using setCurrentBlockState (), currentBlockState () 和 previousBlockState () to handle syntaxes with constructs that span several text blocks

另请参阅 previousBlockState (), setFormat (),和 setCurrentBlockState ().

[protected] int QSyntaxHighlighter:: previousBlockState () const

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.

另请参阅 highlightBlock () 和 setCurrentBlockState ().

[slot] void QSyntaxHighlighter:: rehighlight ()

将高亮重新应用到整个文档。

另请参阅 rehighlightBlock ().

[slot] void QSyntaxHighlighter:: rehighlightBlock (const QTextBlock & block )

将高亮重新应用到给定 QTextBlock block .

另请参阅 rehighlight ().

[protected] void QSyntaxHighlighter:: setCurrentBlockState ( int newState )

Sets the state of the current text block to newState .

另请参阅 currentBlockState () 和 highlightBlock ().

[protected] void QSyntaxHighlighter:: setCurrentBlockUserData ( QTextBlockUserData * data )

附加给定 data to the current text block. The ownership is passed to the underlying text document, i.e. the provided QTextBlockUserData object will be deleted if the corresponding text block gets deleted.

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 QChar in a simple class derived from QTextBlockUserData :

struct ParenthesisInfo
{
    QChar character;
    int position;
};
struct BlockData : public QTextBlockUserData
{
    QList<ParenthesisInfo> parentheses;
};
					

During cursor navigation in the associated editor, you can ask the current 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.

另请参阅 currentBlockUserData () 和 QTextBlock::setUserData ().

void QSyntaxHighlighter:: setDocument ( QTextDocument * doc )

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

另请参阅 document ().

[protected] void QSyntaxHighlighter:: setFormat ( int start , int count , const QTextCharFormat & format )

This function is applied to the syntax highlighter's current text block (i.e. the text that is passed to the highlightBlock () 函数)。

指定 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 QTextCursor 's functions. Note that the document itself remains unmodified by the format set through this function.

另请参阅 format () 和 highlightBlock ().

[protected] void QSyntaxHighlighter:: setFormat ( int start , int count , const QColor & color )

这是重载函数。

指定 color is applied to the current text block from the start position for a length of count 字符。

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

另请参阅 format () 和 highlightBlock ().

[protected] void QSyntaxHighlighter:: setFormat ( int start , int count , const QFont & font )

这是重载函数。

指定 font is applied to the current text block from the start position for a length of count 字符。

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

另请参阅 format () 和 highlightBlock ().