HoYoCenter/interface/json_edit.py
2024-09-08 20:57:25 +08:00

63 lines
2.3 KiB
Python

from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QColor
from PyQt5.QtCore import QRegularExpression, Qt
class CodeEditor(QTextEdit):
def __init__(self):
super().__init__()
self.setFont(QFont("Courier New", 12))
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_())