Frage

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?

War es hilfreich?

Lösung

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) ;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top