Search code examples
qtqlistview

How to change color of item in QListView


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?


Solution

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