How to change color of item in QListView
Asked Answered
B

1

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?

Betrothed answered 29/7, 2014 at 11:20 Comment(6)
I would call model()->setData(vIndex, QBrush(Qt::red), Qt::ForegroundRole); instead.Billboard
@Billboard Ty.It works fine. But I don't understand why setItemData() doesn't work.Betrothed
What does setItemData() function returns?Billboard
I am not sure, but maybe this will work: vMap.insert(Qt::ForegroundRole, QBrush(Qt::red)); model()->setItemData(vIndex, vMap);?Billboard
@Billboard Nope. It's weird. Nevermind, you gave me the right solution.Thanks again.Betrothed
Did you call emit dataChanged after setting item data with setItemData?Conformal
S
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) ;
Siracusa answered 29/7, 2014 at 12:45 Comment(4)
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.Betrothed
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.Siracusa
It should support all Qt::ItemDataRole which contains Qt::ForegroundRole. Whatever it's weird. Maybe a bug.Betrothed
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!Siracusa

© 2022 - 2024 — McMap. All rights reserved.