pyqt SyntaxHighlighter 正则表达式
时间: 2023-10-22 07:20:09 浏览: 176
PyQt中的`QSyntaxHighlighter`类可以用于对文本进行语法高亮显示。其实现原理是使用正则表达式匹配文本中的关键字,然后对匹配到的文本进行高亮处理。
以下是一个简单的示例,使用`QSyntaxHighlighter`类实现对Python代码中的关键字进行高亮显示:
```python
import sys
from PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
from PyQt5.QtWidgets import QApplication, QTextEdit
class PythonHighlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(PythonHighlighter, self).__init__(parent)
self.highlighting_rules = []
keyword_format = QTextCharFormat()
keyword_format.setForeground(QColor(255, 0, 0))
keyword_format.setFontWeight(QFont.Bold)
keywords = ["and", "as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "False",
"finally", "for", "from", "global", "if", "import",
"in", "is", "lambda", "None", "nonlocal", "not",
"or", "pass", "raise", "return", "True", "try",
"while", "with", "yield"]
for word in keywords:
pattern = "\\b" + word + "\\b"
rule = (pattern, keyword_format)
self.highlighting_rules.append(rule)
self.number_format = QTextCharFormat()
self.number_format.setForeground(QColor(0, 128, 0))
pattern = "\\b[0-9]+\\.?[0-9]*\\b"
rule = (pattern, self.number_format)
self.highlighting_rules.append(rule)
self.string_format = QTextCharFormat()
self.string_format.setForeground(QColor(128, 0, 128))
pattern = "\".*\""
rule = (pattern, self.string_format)
self.highlighting_rules.append(rule)
def highlightBlock(self, text):
for pattern, format in self.highlighting_rules:
expression = QRegularExpression(pattern)
match_iterator = expression.globalMatch(text)
while match_iterator.hasNext():
match = match_iterator.next()
self.setFormat(match.capturedStart(), match.capturedLength(), format)
if __name__ == '__main__':
app = QApplication(sys.argv)
editor = QTextEdit()
highlighter = PythonHighlighter(editor.document())
editor.show()
sys.exit(app.exec_())
```
上述示例中,定义了一个名为`PythonHighlighter`的类,继承自`QSyntaxHighlighter`类。在`__init__`方法中,定义了三种高亮格式:关键字、数字和字符串。其中关键字的正则表达式使用了`\\b`来限制匹配单词边界,数字的正则表达式使用了`[0-9]+\\.?[0-9]*`,可以匹配整数和小数,字符串的正则表达式使用了`\".*\"`,可以匹配双引号括起来的任意字符串。
在`highlightBlock`方法中,根据预定义的正则表达式规则,对当前文本块中匹配到的文本进行相应的格式设置,从而实现语法高亮显示。最后在主函数中创建一个`QTextEdit`对象,并将其关联到自定义的`PythonHighlighter`对象上,运行程序即可看到效果。
阅读全文