在这种情况下使用qss是不合适的,因为它们有很多限制,所以实现委托是合适的,在这种情况下是从QStyledItemDelegate继承的类。但在此之前,我们必须通过QTableWidgetItem的setData方法保存颜色信息:
it = QTableWidgetItem("some_text")
it.setData(Qt.UserRole, some_color)
然后是
QStyledItemDelegate
将被覆盖,并更改选择颜色:
class ColorDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
color = index.data(Qt.UserRole)
option.palette.setColor(QPalette.Highlight, color)
QStyledItemDelegate.paint(self, painter, option, index)
然后建立代表:
your_qtablewidget.setItemDelegate(ColorDelegate())
下面是一个完整的示例:
from PyQt5.QtWidgets import QApplication, QStyledItemDelegate, QTableWidget, QTableWidgetItem, QStyle
from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtCore import qrand, Qt
class ColorDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
color = index.data(Qt.UserRole)
option.palette.setColor(QPalette.Highlight, color)
QStyledItemDelegate.paint(self, painter, option, index)
def fun(n_rows, n_columns):
return [[QColor(qrand() % 256, qrand() % 256, qrand() % 256) for i in range(n_rows)] for j in range(n_columns)]
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
n_rows, n_columns = 10, 10
colors = fun(n_rows, n_columns)
w = QTableWidget()
w.setColumnCount(n_columns)
w.setRowCount(n_columns)
for i in range(w.rowCount()):
for j in range(w.columnCount()):
it = QTableWidgetItem("{}-{}".format(i, j))
it.setData(Qt.UserRole, colors[i][j])
w.setItem(i, j, it)
w.setItemDelegate(ColorDelegate())
w.show()
sys.exit(app.exec_())