开发者

In Qt how do I reset the background colour of an item in a ListView from the Model?

开发者 https://www.devze.com 2023-04-11 05:59 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号