Skip to main content
 首页 » 编程设计

python之PyQt Tableview 行背景颜色基于单元格值

2024年10月01日8傻小

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

我发现设置交替行的背景很简单,但我想为其中一列与特定值匹配的行设置背景(即 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 的文档让我陷入困境!)。

你能帮忙吗?

请您参考如下方法:

我们必须获取存档列中的数据(在我的示例中是第三个)并验证它是否满足条件(在本例中为 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,其中没有 bool 数据但模拟数据类型 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) 

总之使用下面的代码,另外完整的代码是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) 

截图: