Python 基于单元格值的PyQt Tableview行背景颜色

Python 基于单元格值的PyQt Tableview行背景颜色,python,qt,pyqt,pyqt4,pyqt5,Python,Qt,Pyqt,Pyqt4,Pyqt5,我正在使用Python3+和Qt5(尽管很高兴有Py2.7和Qt4的答案!)。 完全被关于样式、委托、模型和其他一切的大量文档弄糊涂了 我发现设置备用行的背景很简单,但我想为一列与特定值匹配的行设置背景(即Archive==True) 备用行: self.plainModel = QSqlQueryModel() self.create_model() self.linksTable.setModel(self.plainModel) self.linksTable.setAlternating

我正在使用Python3+和Qt5(尽管很高兴有Py2.7和Qt4的答案!)。 完全被关于样式、委托、模型和其他一切的大量文档弄糊涂了

我发现设置备用行的背景很简单,但我想为一列与特定值匹配的行设置背景(即
Archive==True

备用行:

self.plainModel = QSqlQueryModel()
self.create_model()
self.linksTable.setModel(self.plainModel)
self.linksTable.setAlternatingRowColors(True)
self.linksTable.setStyleSheet("alternate-background-color: Lightgrey;background-color: white;")
self.linksTable.resizeColumnsToContents()
我已经看到一个示例演示了如何执行此操作,但这个特定示例似乎只是简单地复制了备用行结果,并且在开始编写代码几天后,我不知道如何将其转换为检查归档列

摘录自:

我找到了另一个,但目前还没想清楚

特别是我仍然不明白你将如何选择哪些行得到改变,也不明白如何应用一个简单的背景颜色作为“选项”!(阅读有关QStyleOptionViewItem的文档让我陷入困境!)


您能提供帮助吗?

我们必须获取存档列中的数据(在我的示例中是第三个),并验证它是否满足条件(在本例中为true),如果满足条件,我们将返回具有所需颜色的
QBrush
对象

def data(self, item, role):
    if role == Qt.BackgroundRole:
        if QSqlQueryModel.data(self, self.index(item.row(), 3), Qt.DisplayRole):
            return QBrush(Qt.yellow)
    return QSqlQueryModel.data(self, item, role)
同样,在我的例子中,使用数据库SQLITE,其中没有布尔数据,但使用数据类型int进行模拟,将其限制为值0或1,因此使用以下指令,其中它分别根据1或0返回True或False

def data(self, item, role):
    [...]
    if role == Qt.DisplayRole:
        if item.column() == 3:
            return True if QSqlQueryModel.data(self, item, Qt.DisplayRole) == 1 else False
    return QSqlQueryModel.data(self, item, role)
简而言之,使用以下代码,另外完整的代码是:

截图:


完美-如果您感兴趣,我已经添加了一个后续问题。我没有把它作为一个讨论,因为你已经完全回答了这个问题。我想看看存储库中的代码,它还在附近吗?看起来存储库已经更改了
def data(self, item, role):
    [...]
    if role == Qt.DisplayRole:
        if item.column() == 3:
            return True if QSqlQueryModel.data(self, item, Qt.DisplayRole) == 1 else False
    return QSqlQueryModel.data(self, item, role)
def data(self, item, role):
    if role == Qt.BackgroundRole:
        if QSqlQueryModel.data(self, self.index(item.row(), 3), Qt.DisplayRole):
            return QBrush(Qt.yellow)
    if role == Qt.DisplayRole:
        if item.column() == 3:
            return True if QSqlQueryModel.data(self, item, Qt.DisplayRole) == 1 else False
    return QSqlQueryModel.data(self, item, role)