QSyntaxHighlighter 類

QSyntaxHighlighter 類允許您定義句法高亮規則,此外,還可以使用該類查詢文檔的當前格式或用戶數據。 更多...

頭: #include <QSyntaxHighlighter>
qmake: QT += gui
Since: Qt 4.1
繼承: QObject

該類在 Qt 4.1 引入。

注意: 此類的所有函數 可重入 .

公共函數

QSyntaxHighlighter (QTextDocument * parent )
QSyntaxHighlighter (QObject * 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);
    }
}
					

某些句法可以擁有跨多個文本塊的結構。例如,C++ 句法高亮應該能夠對付 / *...* / 多行注釋。要處理這些情況,有必要知道上一文本塊的結束狀態 (如:在注釋)。

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

成員函數文檔編製

QSyntaxHighlighter:: QSyntaxHighlighter ( QTextDocument * parent )

構造 QSyntaxHighlighter 並將它安裝在 parent 。指定 QTextDocument 還會變為 QSyntaxHighlighter 的所有者。

QSyntaxHighlighter:: QSyntaxHighlighter ( QObject * parent )

構造 QSyntaxHighlighter 采用給定 parent .

若父級為 QTextEdit ,在父級文檔安裝句法高亮器。指定的 QTextEdit 還會變為 QSyntaxHighlighter 的所有者。

[slot] void QSyntaxHighlighter:: rehighlight ()

將高亮重新應用到整個文檔。

該函數在 Qt 4.2 引入。

另請參閱 rehighlightBlock ().

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

將高亮重新應用到給定 QTextBlock block .

該函數在 Qt 4.6 引入。

另請參閱 rehighlight ().

[虛擬] QSyntaxHighlighter:: ~QSyntaxHighlighter ()

析構函數。從文本文檔卸載這種句法高亮器。

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

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

把當前文本塊的狀態設為 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 (檢索使用 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 )

安裝句法高亮器在給定 QTextDocument doc QSyntaxHighlighter 每次隻可以用於 1 文檔。

另請參閱 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 ().