在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))