PyQt Tableview基于单元格值

时间:2017-05-21 19:49:07

标签: python qt pyqt pyqt4 pyqt5

Python(3+)和Qt(5)(虽然很高兴有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()

我已经看到了一个显示如何执行此操作的示例through the model但是这个具体示例似乎只是简单地复制备用行结果,并且几天后我就无法查看代码如何将其转换为检查存档列。

摘自example

elif role == Qt.BackgroundRole:
    if index.row() % 2 == 0:
        return QBrush(Qt.yellow)
elif role != Qt.DisplayRole:
    return QVariant()

我找到了另一个example using delegates,但现在还不能理解它。

特别是我仍然无法理解您将如何选择哪些行获得更改,并且无法理解如何将简单的背景颜色应用为"选项"! (阅读关于QStyleOptionViewItem的文档正在发送我的兔子洞!)。

你能帮忙吗?

1 个答案:

答案 0 :(得分:2)

我们必须获取归档列中的数据(在我的示例中它是第三个)并验证它是否满足条件(在本例中为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,其中没有布尔数据但是使用限制为值0或1的数据类型int进行模拟,因此请使用以下指令,其中它分别根据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)

简而言之,使用以下代码,完整代码为here

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)

截图:

enter image description here

相关问题