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 }
