How to change color of item in QListView

落花浮王杯 提交于 2019-12-11 12:09:55

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25014076/how-to-change-color-of-item-in-qlistview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!