在pyqt5中使用QSyntaxHighlighter可以实现对文本编辑器中的代码进行语法高亮显示。QSyntaxHighlighter是Qt框架中的一个类,用于自定义文本编辑器的语法高亮规则。
QSyntaxHighlighter的使用步骤如下:
from PyQt5.QtGui import QTextDocument, QTextCharFormat, QFont, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit
from PyQt5.QtCore import Qt, QRegExp
from PyQt5.QtSyntaxHighlighter import QSyntaxHighlighter, QRegularExpressionValidator
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
def highlightBlock(self, text):
# 定义关键字的格式
keywordFormat = QTextCharFormat()
keywordFormat.setForeground(Qt.darkBlue)
keywordFormat.setFontWeight(QFont.Bold)
# 定义注释的格式
commentFormat = QTextCharFormat()
commentFormat.setForeground(Qt.darkGreen)
# 定义字符串的格式
stringFormat = QTextCharFormat()
stringFormat.setForeground(Qt.darkRed)
# 定义正则表达式匹配规则
rules = [
(QRegExp("\\bint\\b"), keywordFormat),
(QRegExp("\\bfloat\\b"), keywordFormat),
(QRegExp("\\bstring\\b"), keywordFormat),
(QRegExp("#.*"), commentFormat),
(QRegExp("\".*\""), stringFormat)
]
# 对文本块应用匹配规则
for pattern, format in rules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.highlighter = Highlighter(self.textEdit.document())
通过以上步骤,我们可以在pyqt5中使用QSyntaxHighlighter实现对文本编辑器中的代码进行语法高亮显示。
推荐的腾讯云相关产品:腾讯云服务器(CVM)和腾讯云数据库(TencentDB)。
领取专属 10元无门槛券
手把手带您无忧上云