内容表

上一话题

QSurfaceFormat

下一话题

QTabletEvent

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

Inheritance diagram of PySide2.QtGui.QSyntaxHighlighter

概要

函数

虚函数

详细描述

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

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

在此之后 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 在当前文本块。例如:

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 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() 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”:

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 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() and 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() 文档编制。

class QSyntaxHighlighter ( parent )

QSyntaxHighlighter(parent)

param parent

QObject

构造 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 and installs it on parent 。指定 QTextDocument also becomes the owner of the QSyntaxHighlighter .

PySide2.QtGui.QSyntaxHighlighter. currentBlock ( )
返回类型

QTextBlock

返回当前文本块。

PySide2.QtGui.QSyntaxHighlighter. currentBlockState ( )
返回类型

int

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

PySide2.QtGui.QSyntaxHighlighter. currentBlockUserData ( )
返回类型

QTextBlockUserData

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

PySide2.QtGui.QSyntaxHighlighter. document ( )
返回类型

QTextDocument

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

另请参阅

setDocument()

PySide2.QtGui.QSyntaxHighlighter. format ( pos )
参数

pos int

返回类型

QTextCharFormat

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

另请参阅

setFormat()

PySide2.QtGui.QSyntaxHighlighter. highlightBlock ( text )
参数

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 QSyntaxHighlighter and reimplement . 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:

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)
											

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

PySide2.QtGui.QSyntaxHighlighter. previousBlockState ( )
返回类型

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.

PySide2.QtGui.QSyntaxHighlighter. rehighlight ( )

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

PySide2.QtGui.QSyntaxHighlighter. rehighlightBlock ( block )
参数

block QTextBlock

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

另请参阅

rehighlight()

PySide2.QtGui.QSyntaxHighlighter. setCurrentBlockState ( newState )
参数

newState int

Sets the state of the current text block to newState .

PySide2.QtGui.QSyntaxHighlighter. setCurrentBlockUserData ( data )
参数

data QTextBlockUserData

附加给定 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 :

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)
											

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

PySide2.QtGui.QSyntaxHighlighter. setDocument ( doc )
参数

doc QTextDocument

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

另请参阅

document()

PySide2.QtGui.QSyntaxHighlighter. setFormat ( start , count , color )
参数
  • start int

  • count int

  • color QColor

PySide2.QtGui.QSyntaxHighlighter. setFormat ( start , count , font )
参数
  • start int

  • count int

  • font QFont

PySide2.QtGui.QSyntaxHighlighter. setFormat ( start , count , format )
参数