Question

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

Was it helpful?

Solution

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));

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top