Qtableview单元格颜色修改

 在python环境中,可以自定义Qtableview单元格颜色,包括前景色和背景色。

change_color中按角色设定了颜色值;data中按角色修改颜色值。

class CustomTableModel(QAbstractTableModel):
    def __init__(self):
        super().__init__()

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return self.input_data[index.row()][index.column()]
        elif role == Qt.ForegroundRole:
            if index.row() == 0 and index.column() == 1:  # 第一行字体颜色为红色
                return QColor(Qt.red)
            elif index.row() == 1:  # 第二行字体颜色为绿色
                return QColor(Qt.green)
            color = self.colors.get((index, role))
            if color is not None:
                return color
        elif role == Qt.FontRole:
            # QColor(Qt.red)
            if index.row() == 2:  # 第三行字体大小为15
                font = QFont()
                font.setPointSize(15)
                return font
        elif role == Qt.BackgroundRole:
            color = self.colors.get((index, role))
            if color is not None:
                return color     
            return QColor(Qt.white)
        return None

    def change_color(self, index, color, role=Qt.ForegroundRole):
        if role == Qt.BackgroundRole:
            self.colors[(index, role)] = color
        elif role == Qt.ForegroundRole:
            self.colors[(index, role)] = color
        self.dataChanged.emit(index, role)


class TableWidget(QWidget):
    def __init__(self):
        super().__init__()
    ...

    def set_cell_color(self, index, f_color, b_color, role=Qt.ForegroundRole):
        self.model.change_color(index, b_color, Qt.BackgroundRole)
        self.model.change_color(index, f_color, role)

    @Slot()
    def on_pButton_clicked(self):
        index = self.model.index(6, 1)
        self.set_cell_color(index, QBrush(Qt.red), QBrush(Qt.green))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值