1

I have my own subclass of QListView and I would like to change the color of an item with index mLastIndex . I tried with

QModelIndex vIndex = model()->index(mLastIndex,0) ;
QMap<int,QVariant> vMap;
vMap.insert(Qt::ForegroundRole, QVariant(QBrush(Qt::red))) ;
model()->setItemData(vIndex, vMap) ;

But it didn't change the color, instead, the item wasn't displayed anymore. Any idea about what was wrong?

Mike Shaw
  • 373
  • 7
  • 22

1 Answers1

2

Your code are simply clear all data in model and leaves only value for Qt::ForegroundRole since your map contains only new value.

Do this like that (it will work for most of data models not only standard one):

QModelIndex vIndex = model()->index(mLastIndex,0);
model->setData(vIndex, QBrush(Qt::red), Qt::ForegroundRole);

Or by fixing your code:

QModelIndex vIndex = model()->index(mLastIndex,0) ;
QMap<int,QVariant> vMap = model()->itemData(vIndex);
vMap.insert(Qt::ForegroundRole, QVariant(QBrush(Qt::red))) ;
model()->setItemData(vIndex, vMap) ;
Marek R
  • 32,568
  • 6
  • 55
  • 140
  • 1
    Ty for your answer. It works. But I read in the doc: Roles that are not in roles will not be modified. Well, it's not the case. – Mike Shaw Jul 29 '14 at 12:50
  • This is crappy sentence in documentation. Probably this means that model has to support given role (QStandardItemModel supports all possible roles). Note that you can provide own data model which will support only basic roles like DisplayRole and EditRole. – Marek R Jul 29 '14 at 12:59
  • It should support all Qt::ItemDataRole which contains Qt::ForegroundRole. Whatever it's weird. Maybe a bug. – Mike Shaw Jul 29 '14 at 13:13
  • You don't understand this doesn't mean that map is merged with old values, but that some values from new map can be ignored! – Marek R Jul 29 '14 at 14:00