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 }