如何在PyQt5中预设样式表的QTableView中返回QColor作为QBackgroundRole



我遇到了一个标题中提到的奇怪问题。

我有一个QTableView。

self.table = QTableView()

然后设置一些QSS。

self.table.setStyleSheet('''
QTableView {
border: 2px solid red;
padding: 5px;
border-radius: 5px;
gridline-color: red;
color: red;
}
QTableView::item{
border-color: none;
padding-left: 5px;
padding-right: 5px;
gridline-color: rgb(44, 49, 60);
border-bottom: 1px solid green;
}
QTableView::item:selected{
background-color: blue;
}
''')

然后我尝试在模型中返回一个QColor(QAbstractTableModel(,它就是不起作用。如果我删除了样式表,那么它就起作用了。我的QSS哪一行有人制造了这个问题吗?

if role == Qt.BackgroundRole and index.row() == self.headStart:
# Set header start color
return QColor(208, 74, 2)

我需要样式表,同时我也需要Q.BackgroundRole来工作。

这似乎是一个部分已知且未解决的错误,当为::item选择器指定背景色或边框时,颜色角色将被忽略(因为它被样式表覆盖(。

一个可能的解决方案是在调用默认实现之前设置一个项委托并填充底层矩形

class BackgroundDelegate(QtWidgets.QStyledItemDelegate):
def paint(self, qp, opt, index):
if index.data(QtCore.Qt.BackgroundRole):
qp.fillRect(opt.rect, index.data(QtCore.Qt.BackgroundRole))
super().paint(qp, opt, index)
class SomeClass(QtWidgets.QWidget):
def __init__(self):
# ...
self.table = QtWidgets.QTableView()
self.delegate = BackgroundDelegate(self.table)
self.table.setItemDelegate(self.delegate)

如果由于某些操作系统样式问题而无法正常工作,请尝试为基本项选择器设置background: transparent

最新更新