Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...