QTableView change row color based on a value

7.7k views Asked by At

I have a QTableView that I implemented with my own model subclassed from QAbstractTableModel. I want to be able to change the row color to red when one of the fields in the row has a certain value. I saw a lot of examples where the answer is to call the models setData and use Qt::BackgroundRole to change the background color. Since I subclassed the AbstractTableModel I reimplemented setData and data so calling models setData does nothing with the background color role since I'm only handling data whose role is Qt::DisplayRole.

I guess my first question is : Is there an easier way to change the color of the entire role? If not, I'm guessing I have to implement that part in setData and data to handle the BackgroundRole which I have no idea how to do so if anyone has examples on how to do this it would really help a lot...

2

There are 2 answers

0
MBU On BEST ANSWER

That was easier than i thought... In my data method i added a check for

if (role == Qt::BackgroundColorRole) 

In that if block. i check do the value comparison to see if thats the row i have to change the color for and if it is i return:

return QVariant(QColor(Qt::red));
1
UpAndAdam On

A better answer is to use a delegate provided by the view for this task and not to touch the model at all. Why should the model know anything about what color you want the view to be? What happens if you want multiple views to behave differently? ETC.

You can use setColumnDelegate, or setRowDelegate or a number of other mechanisms. Take a look at those functions for complete answer.