In Qt I have a QListView
that is using a custom Model class that contains the data to display. Based on the data, I want the background (and eventually the foregroun开发者_运维问答d/text) colour to be set to match the state of the data.
So far I have accomplished this by returning a QBrush
with the selected QColor
inside of a QVariant
for the Qt::BackgroundRole
in the QAbstractListModel::data()
method, like so:
QVariant CustomListModel::data(const QModelIndex& index, int role) const
{
Item& item = findItem(index);
if (item)
{
// ...
if (role == Qt::BackgroundRole)
{
return QVariant(QBrush(item.color()));
}
// ...
}
}
The problem that I am having is that I want to be able to reset the colour back to the widget's default background colour when the item's state becomes 'neutral', but I have been unable to find the correct instructions to do this. What is the canonical way to accomplish this?
Try something like this in your data method:
if (role == Qt::BackgroundRole)
{
bool itemStateIsNeutral = ...
if (itemStateIsNeutral) return QVariant();
// else:
return QVariant(QBrush(item.color()));
}
You might have to do return QVariant(QBrush())
instead, I'm not sure about this.
精彩评论