How to change item color in QListView

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

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

But this did not change the color; instead, the element was no longer displayed. Any idea on what was wrong?

+1
source share
1 answer

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

Do it like this (this will work for most data models, not just the standard):

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

Or by correcting 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) ; 
+2
source

Source: https://habr.com/ru/post/1011880/


All Articles