QSyntaxHighlighter 类

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. 更多...

头: #include <QSyntaxHighlighter>
qmake: QT += gui
Since: Qt 4.1
继承: 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 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.

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

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 ,希望应用句法高亮。例如:

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

在此之后 highlightBlock () 函数会被自动调用 (每当必要时)。使用 highlightBlock () function to apply formatting (e.g. setting the font and color) to the text that is passed to it. 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 ().

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 句法高亮范例 .

成员函数文档编制

QSyntaxHighlighter:: QSyntaxHighlighter ( QObject * parent )

构造 QSyntaxHighlighter 采用给定 parent .

If the parent is a QTextEdit , it installs the syntax highlighter on the parents document. The specified QTextEdit also becomes the owner of the QSyntaxHighlighter .

QSyntaxHighlighter:: QSyntaxHighlighter ( QTextDocument * parent )

构造 QSyntaxHighlighter and installs it on parent 。指定 QTextDocument also becomes the owner of the QSyntaxHighlighter .

[virtual] QSyntaxHighlighter:: ~QSyntaxHighlighter ()

Destructor. Uninstalls this syntax highlighter from the text document.

[protected] QTextBlock QSyntaxHighlighter:: currentBlock () const

返回当前文本块。

该函数在 Qt 4.4 引入。

[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 ()

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

该函数在 Qt 4.2 引入。

另请参阅 rehighlightBlock ().

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

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

该函数在 Qt 4.6 引入。

另请参阅 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 char;
    int position;
};
struct BlockData : public QTextBlockUserData
{
    QVector<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 ().