I have my own subclass of QListView and I would like to change the color of an item with index mLastIndex . I tried with
我有我自己的QListView子类,我想用索引mLastIndex改变条目的颜色。我试着用
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 个解决方案
#1
2
Your code are simply clear all data in model and leaves only value for Qt::ForegroundRole
since your map contains only new value.
您的代码只是清除模型中的所有数据,并且只保留Qt::ForegroundRole的值,因为您的映射只包含新值。
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) ;
#1
2
Your code are simply clear all data in model and leaves only value for Qt::ForegroundRole
since your map contains only new value.
您的代码只是清除模型中的所有数据,并且只保留Qt::ForegroundRole的值,因为您的映射只包含新值。
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) ;