QTableView中修改某个单元格或者行或者列内容颜色

QTableView的单元格内容实现还是继承了TableViewModel类的data(const QModelIndex &index, int role) const函数,那个设置颜色的问题也就在这个里面实现了。

 
1、设置某个单元格颜色
 
复制代码
 1 QVariant TableViewModel::data(const QModelIndex &index, int role) const
 2 {
 3     if (!index.isValid())
 4         return QVariant();
 5     if (index.row() >= fEntries.size() || index.row() < 0)
 6         return QVariant();
 7     if(role == Qt::DisplayRole) {
 8         const Entry& entry = fEntries.at(index.row());
 9         const QString& key = getColumnId(index.column());
10         return entry.value(key);
11     }
12     if(role == Qt::BackgroundRole)
13     {
14         if((1 == index.column())&(fEntries[index.row()].value("LandType") == QString::fromLocal8Bit("登陆失败")))
15         {
16             return QVariant(Qt::GlobalColor(Qt::red));
17         }
18         else if(((1 == index.column())&(fEntries[index.row()].value("LandType") == QString::fromLocal8Bit("登陆成功"))))
19         {
20             return QVariant(Qt::GlobalColor(Qt::green));
21         }
22     }
23     return QVariant();
24 }
复制代码

 


我这个上面其实是有两种状态,根据里面的内容来显示颜色的变化,单元格的锁定时(index.column()和index.row()).
既然能锁定某个单个元格,那个锁定某一行或者一列也很简单。


2、设置某行颜色
 
复制代码
 1 QVariant TableViewModel::data(const QModelIndex &index, int role) const
 2 {
 3     if (!index.isValid())
 4         return QVariant();
 5     if (index.row() >= fEntries.size() || index.row() < 0)
 6         return QVariant();
 7     if(role == Qt::DisplayRole) {
 8         const Entry& entry = fEntries.at(index.row());
 9         const QString& key = getColumnId(index.column());
10         return entry.value(key);
11     }
12     if(role == Qt::BackgroundRole)
13     {
14         if(1 == index.row())
15         {
16             return QVariant(Qt::GlobalColor(Qt::red));
17         }
18     }
19     return QVariant();
20 }
复制代码

 


3、设置某列颜色
 
复制代码
 1 QVariant TableViewModel::data(const QModelIndex &index, int role) const
 2 {
 3     if (!index.isValid())
 4         return QVariant();
 5     if (index.row() >= fEntries.size() || index.row() < 0)
 6         return QVariant();
 7     if(role == Qt::DisplayRole) {
 8         const Entry& entry = fEntries.at(index.row());
 9         const QString& key = getColumnId(index.column());
10         return entry.value(key);
11     }
12     if(role == Qt::BackgroundRole)
13     {
14         if(1 == index.column())
15         {
16             return QVariant(Qt::GlobalColor(Qt::red));
17         }
18     }
19     return QVariant();
20 }
复制代码

 

posted @   FelixWang  阅读(18780)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示