from PyQt5.QtWidgets import QApplication, QTextEdit from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QFontMetrics from PyQt5.QtCore import QRegularExpression, Qt class CodeEditor(QTextEdit): def __init__(self, text:str=""): super().__init__() self.setFont(QFont("Courier New", 12)) fontMetrics = QFontMetrics(self.font()) tabWidth = 4 * fontMetrics.width(' ') # Calculate the width of a tab self.setTabStopWidth(tabWidth) self.setPlainText(text) self.highlighter = CodeHighlighter(self.document()) self.highlighter.rehighlight() def paste(self): super().paste() self.highlighter.rehighlight() class CodeHighlighter(QSyntaxHighlighter): def __init__(self, document): super().__init__(document) self.highlightingRules = [] # 定义 JSON 高亮规则 self.keyFormat = QTextCharFormat() self.keyFormat.setForeground(Qt.GlobalColor.darkBlue) self.keyFormat.setFontWeight(QFont.Bold) self.valueFormat = QTextCharFormat() self.valueFormat.setForeground(Qt.GlobalColor.darkGreen) self.boolFormat = QTextCharFormat() self.boolFormat.setForeground(Qt.GlobalColor.red) self.numberFormat = QTextCharFormat() self.numberFormat.setForeground(Qt.GlobalColor.darkCyan) # 创建蓝色格式 blueFormat = QTextCharFormat() blueFormat.setForeground(Qt.GlobalColor.blue) self.rules = [ (QRegularExpression(r'\b(true|false|null)\b'), self.boolFormat), (QRegularExpression(r'\b(-?\d+\.?\d*)\b'), self.numberFormat), (QRegularExpression(r'\{'), blueFormat), (QRegularExpression(r'\}'), blueFormat), (QRegularExpression(r'\['), blueFormat), (QRegularExpression(r'\]'), blueFormat), (QRegularExpression(r'\"(\\.|[^"\\])*\"'), self.valueFormat), (QRegularExpression(r'\b(\w+)\s*:'), self.keyFormat) ] def highlightBlock(self, text): for pattern, format in self.rules: expression = QRegularExpression(pattern) matchIterator = expression.globalMatch(text) while matchIterator.hasNext(): match = matchIterator.next() self.setFormat(match.capturedStart(), match.capturedLength(), format) if __name__ == "__main__": import sys app = QApplication(sys.argv) editor = CodeEditor() editor.show() sys.exit(app.exec_())