HoYoCenter/interface/json_edit.py
moyanj 11e843bff3 实现深色模式支持和配置文件路径更新
- 为代码编辑器和主窗口实现深色模式样式,以增强黑暗环境下的用户体验。
- 更新配置文件的读取路径。
2024-09-09 16:10:46 +08:00

75 lines
2.9 KiB
Python

from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QFontMetrics, QColor
from PyQt5.QtCore import QRegularExpression, Qt
import app.env as env
class CodeEditor(QTextEdit):
def __init__(self, text:str=""):
super().__init__()
self.setFont(QFont("Courier New", 12))
fontMetrics = QFontMetrics(self.font())
tabWidth = 4 * fontMetrics.width(' ') # 计算tab的宽度
self.setTabStopWidth(tabWidth)
self.setPlainText(text)
self.highlighter = CodeHighlighter(self.document())
self.highlighter.rehighlight()
if env.config.theme== "dark":
# 设置深色模式的样式
self.setStyleSheet("""
background-color: #2b2b2b; /* 背景颜色 */
color: #ffffff; /* 文本颜色 */
selection-background-color: #4e9a06; /* 选中背景颜色 */
selection-color: #ffffff; /* 选中文本颜色 */
""")
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(QColor("#0000ff")) # 蓝色关键字
self.keyFormat.setFontWeight(QFont.Bold)
self.valueFormat = QTextCharFormat()
self.valueFormat.setForeground(QColor("#008000")) # 绿色字符串值
self.boolFormat = QTextCharFormat()
self.boolFormat.setForeground(QColor("#ff0000")) # 红色布尔值
self.numberFormat = QTextCharFormat()
self.numberFormat.setForeground(QColor("#008080")) # 青色数字
# 创建蓝色格式
blueFormat = QTextCharFormat()
blueFormat.setForeground(QColor("#0000ff"))
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_())