最近在使用qt完成大作业的时候,遇到了这个问题:如何设置tableView中某一项的颜色
如图,我希望状态那一栏在空闲时是绿色,被预约时是红色
网上常见的解决方案
网上最常见的方案是使用QStandardItemModel中的item()->setForeground方法,来实现设置颜色
例如,在文章https://blog.csdn.net/qq_26093511/article/details/82861767中就用到了此方法
QStandardItemModel *student_model = new QStandardItemModel();
......
student_model->item(0, 1)->setForeground(QBrush(QColor(255, 0, 0)));
但是,我们是使用了自定义的model,所以我们并不能使用这个方法
向底层寻找答案
在网上找寻答案无果后,我想到:qt是使用了类似于MVC的设计模式,其中的Delegate是负责做视图绘制的,那说不定可以通过Delegate来实现文本颜色的更改
通过查询QItemDelegate的api文档,我注意到了一个名叫pain的函数
上网搜索相关资料,再结合一些简单的实验后,发现,可以通过重写paint函数,改动其中的option变量,来实现控制视图绘制的效果
例如
void BeanDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
if(!index.isValid())
return;
QStyleOptionViewItem so = option;
//在这里通过修改so中的某些参数来实现绘制方式的修改
QItemDelegate::paint(painter,so,index);
}
解决方法
通过设置so中的palette,调用so.palette.setColor,即可设置文本颜色
完整代码为
void BeanDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
if(!index.isValid())
return;
QStyleOptionViewItem so = option;
so.palette = QPalette();
so.palette.setColor(QPalette::Text,QColor(255,0,0));
QItemDelegate::paint(painter,so,index);
}
这样在测试程序中,所有的文本都是红色的了
如果需要指定的单元格变颜色,只需要使用index变量判断列与行即可
总结
遇到此类问题,尽量去网上查找相关的资料,能直接利用自然是最好的,如果不能直接利用,也可以从中提取到一些后面会用到的关键信息(例如上文中的QBrush(QColor(255, 0, 0))
这个代码段,知道了这个就省下了再去查QBrush的api的时间)
如果网上没有完全适用于自己的方法,则需要根据自己对于这个框架的理解,去尝试从更底层的地方出发寻找思路,并不断通过实验来验证自己的思路,最终找到解决方法