如何在QListView中更改项目的颜色 [英] How to change color of item in QListView

查看:150
本文介绍了如何在QListView中更改项目的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我自己的QListView子类,我想更改带有索引mLastIndex的项目的颜色.我尝试过

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?

推荐答案

您的代码只是清除了模型中的所有数据,并且仅保留了Qt::ForegroundRole的值,因为您的地图仅包含新值.

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

或通过修复代码:

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

这篇关于如何在QListView中更改项目的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆