# log_style_manager.py from PySide6.QtGui import QTextDocument, QTextBlockFormat, QTextCharFormat, QFont, QColor from PySide6.QtCore import Qt from PySide6.QtGui import QTextCursor class LogStyleManager: """ 日志样式管理器,统一控制 QTextEdit 的字体、颜色、行间距等 """ def __init__(self, text_edit): self.text_edit = text_edit self.default_font = self.text_edit.font() self.default_style = { 'default': {'color': 'white', 'bold': False}, 'info': {'color': 'cyan', 'bold': False}, 'warning': {'color': 'yellow', 'bold': False}, 'error': {'color': 'red', 'bold': False}, 'trigger': {'color': '#28a745', 'bold': False}, } def set_log_type_mapping(self, mapping=None): """ 设置日志类型与样式的映射关系 :param mapping: dict,键为日志类型(如 'info'),值为对应的样式字典 样式字典支持: - color: 颜色字符串 - bold: 是否加粗 - background: 背景颜色(可选) - italic: 是否斜体 """ default_mapping = { 'default': {'color': 'white', 'bold': False}, 'info': {'color': 'cyan', 'bold': False}, 'warning': {'color': 'yellow', 'bold': False}, 'error': {'color': 'red', 'bold': True}, # 错误信息加粗 'trigger': {'color': '#28a745', 'bold': False}, 'debug': {'color': 'gray', 'italic': True} # 新增 debug 类型 } # 如果传入了新的映射规则,则更新默认样式 if mapping is not None: self.default_style = mapping else: self.default_style = default_mapping def set_global_font(self, font_family="微软雅黑", font_size=13): """设置全局字体""" self.default_font.setFamily(font_family) self.default_font.setPointSize(font_size) self.text_edit.setFont(self.default_font) def set_letter_spacing(self, spacing=5): """设置字间距""" self.default_font.setLetterSpacing(QFont.SpacingType.AbsoluteSpacing, spacing) self.text_edit.setFont(self.default_font) def set_line_height(self, line_height=150): """设置段落行高(百分比)""" doc = self.text_edit.document() block_format = QTextBlockFormat() block_format.setLineHeight(float(line_height), 0) block_format.setTopMargin(0) block_format.setBottomMargin(0) cursor = QTextCursor(doc) cursor.select(QTextCursor.SelectionType.Document) # 修改此处 cursor.mergeBlockFormat(block_format) cursor.clearSelection() def apply_log_style(self, log_type='default'): """返回适用于当前日志类型的 QTextCharFormat""" style = self.default_style.get(log_type.lower(), self.default_style['default']) fmt = QTextCharFormat() fmt.setForeground(QColor(style['color'])) if style.get('bold', False): fmt.setFontWeight(QFont.Weight.Bold) return fmt def insert_log(self, message, log_type='default'): """插入带样式的日志信息""" fmt = self.apply_log_style(log_type) cursor = self.text_edit.textCursor() cursor.movePosition(QTextCursor.End) cursor.mergeCharFormat(fmt) cursor.insertText(message + "\n") self.text_edit.setTextCursor(cursor) self.text_edit.ensureCursorVisible() def reset_styles(self): """重置所有样式到默认状态""" self.text_edit.setStyleSheet("") self.text_edit.setFont(self.default_font) self.set_line_height(100)