HoYoCenter/interface/json_edit.py

67 lines
2.5 KiB
Python
Raw Normal View History

2024-09-08 20:57:25 +08:00
from PyQt5.QtWidgets import QApplication, QTextEdit
2024-09-08 21:14:02 +08:00
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QFontMetrics
2024-09-08 20:57:25 +08:00
from PyQt5.QtCore import QRegularExpression, Qt
class CodeEditor(QTextEdit):
2024-09-08 21:14:02 +08:00
def __init__(self, text:str=""):
2024-09-08 20:57:25 +08:00
super().__init__()
self.setFont(QFont("Courier New", 12))
2024-09-08 21:14:02 +08:00
fontMetrics = QFontMetrics(self.font())
tabWidth = 4 * fontMetrics.width(' ') # Calculate the width of a tab
self.setTabStopWidth(tabWidth)
self.setPlainText(text)
2024-09-08 20:57:25 +08:00
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_())