# StatusStyleDelegate.py from PySide6.QtWidgets import QStyledItemDelegate from PySide6.QtGui import QColor, QFont, QBrush from PySide6.QtCore import Qt, QTimer from PySide6.QtGui import QPalette class StatusStyleDelegate(QStyledItemDelegate): def __init__(self, parent=None, table_view=None): super().__init__(parent) self.flash_cells = {} # 存储需要闪烁的单元格 {(row, col): timer} self.flash_duration = 500 # 闪烁持续时间(毫秒) self.updated_cells = set() # 存储需要高亮的单元格 (row, col) self.table_view = table_view # 保存 QTableView 实例 def flash_cell(self, row, column): # 如果单元格已经在闪烁,重置计时器 if (row, column) in self.flash_cells: self.flash_cells[(row, column)].stop() # 创建新的计时器 timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(lambda: self.end_flash(row, column)) self.flash_cells[(row, column)] = timer timer.start(500) self.updated_cells.add((row, column)) if self.table_view: self.table_view.viewport().update() def end_flash(self, row, column): """1秒后清除高亮""" if (row, column) in self.flash_cells: del self.flash_cells[(row, column)] self.updated_cells.discard((row, column)) if self.table_view: self.table_view.viewport().update() def initStyleOption(self, option, index): super().initStyleOption(option, index) # 检查是否需要闪烁 row = index.row() col = index.column() if (row, col) in self.updated_cells: option.backgroundBrush = QBrush(QColor("yellow")) model = index.model() status_index = model.index(index.row(), 7) status = model.data(status_index, Qt.ItemDataRole.DisplayRole) if status == "已触发": option.font = QFont("Arial", 14, QFont.Weight.Bold) option.palette.setColor(QPalette.ColorRole.Text, QColor('red')) option.backgroundBrush = QBrush(QColor('lightcoral')) # 背景色 elif status == "错买": option.font = QFont("Arial", 14, QFont.Weight.Bold) option.palette.setColor(QPalette.ColorRole.Text, QColor('green')) # 文字颜色 option.backgroundBrush = QBrush(QColor('lightgreen')) # 背景色 elif status == "监控中": option.font = QFont("Arial", 12, QFont.Weight.Normal) option.palette.setColor(QPalette.ColorRole.Text, QColor('black')) option.backgroundBrush = QBrush(QColor('white')) else: option.font = QFont("Arial", 12, QFont.Weight.Normal) option.palette.setColor(QPalette.ColorRole.Text, QColor('black')) option.backgroundBrush = QBrush(QColor('white')) # 新增对获利列的处理 if index.column() == 6: # 检查是否为获利列 option.font = QFont(option.font().family(), option.font().pointSize(), QFont.Weight.Bold) profit_text = model.data(index, Qt.ItemDataRole.DisplayRole) try: profit_value = float(profit_text.replace('%', '')) # 移除百分号再转换 if profit_value > 0: option.palette.setColor(QPalette.ColorRole.Text, QColor('red')) elif profit_value < 0: option.palette.setColor(QPalette.ColorRole.Text, QColor('green')) except ValueError: pass # 如果转换失败,保持默认颜色