pyqt SyntaxHighlighter 怎么使用
时间: 2023-10-24 08:11:31 浏览: 166
PyQt中的`QSyntaxHighlighter`类可以用于在`QPlainTextEdit`或`QTextEdit`中高亮显示文本。下面是一个简单的示例:
```python
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit
import sys
class PythonHighlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(PythonHighlighter, self).__init__(parent)
keywordFormat = QTextCharFormat()
keywordFormat.setForeground(QColor(200, 111, 0))
keywordFormat.setFontWeight(QFont.Bold)
keywords = ["False", "None", "True", "and", "as", "assert", "async",
"await", "break", "class", "continue", "def", "del", "elif",
"else", "except", "finally", "for", "from", "global", "if",
"import", "in", "is", "lambda", "nonlocal", "not", "or",
"pass", "raise", "return", "try", "while", "with", "yield"]
self.highlightingRules = [(QRegExp("\\b" + keyword + "\\b"), keywordFormat)
for keyword in keywords]
self.numberFormat = QTextCharFormat()
self.numberFormat.setForeground(QColor(255, 0, 0))
self.highlightingRules.append((QRegExp("\\b[0-9]+\\b"), self.numberFormat))
self.stringFormat = QTextCharFormat()
self.stringFormat.setForeground(QColor(0, 128, 0))
self.highlightingRules.append((QRegExp("\".*\""), self.stringFormat))
self.highlightingRules.append((QRegExp("\'.*\'"), self.stringFormat))
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout(window)
editor = QTextEdit()
layout.addWidget(editor)
highlighter = PythonHighlighter(editor.document())
window.show()
sys.exit(app.exec_())
```
在这个例子中,我们继承了`QSyntaxHighlighter`类,并在`highlightBlock()`函数中定义了一些高亮显示规则。例如,我们使用`QRegExp`匹配关键字、数字和字符串,并使用不同的颜色和字体格式来显示它们。
在主函数中,我们创建了一个`QTextEdit`控件并将其添加到布局中。然后,我们创建了一个`PythonHighlighter`对象,并将其附加到编辑器的文档中。
运行这个例子,你将看到一个简单的文本编辑器,它可以高亮显示Python代码的关键字、数字和字符串。
阅读全文