Alan Alan - 1 year ago 56
Python Question

PyQt Tableview background color based on text value rather than True or False

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.

Answer Source

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)

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download