基于文本值而不是 True 或 False 的 PyQt Tableview 背景颜色 [英] PyQt Tableview background color based on text value rather than True or False
本文介绍了基于文本值而不是 True 或 False 的 PyQt Tableview 背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
跟进
Follow up to my general question, where @eyllanesc has kindly answered my question.
Out of curiosity, I tried changing to code to check against a string rather than 1 and all the rows turned gray.
Original code from @eyllanesc:
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)
If I change it to
def data(self, item, role):
if role == Qt.BackgroundRole:
if QSqlQueryModel.data(self, self.index(item.row(), 2), Qt.DisplayRole):
return QBrush(Qt.yellow)
if role == Qt.DisplayRole:
if item.column() == 2:
return True if QSqlQueryModel.data(self, item, Qt.DisplayRole) == 'Young' else False
return QSqlQueryModel.data(self, item, role)
then all the rows turn yellow.
What gives? Will anyone help me understand?
N.B. I'm aware that a non-empty python string will be equivalent to True
N.B. I can replicate the desired behaviour by adding another column to the SQL query (using CASE WHEN etc.) and then using setColumnHidden(col, True) to hide the test column.
解决方案
You should check the condition inside if role == Qt.BackgroundRole
def data(self, item, role):
if role == Qt.BackgroundRole:
if QSqlQueryModel.data(self, self.index(item.row(), 2), Qt.DisplayRole) == "Young":
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)
这篇关于基于文本值而不是 True 或 False 的 PyQt Tableview 背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文