2016-11-09 280 views
0

我知道有很多關於論壇的討論和關於這個主題的討論,但是我找不到這個問題的工作解決方案。QTableView設置特定行的顏色

我有一個使用模型的QTableView。我需要能夠通過模型更改某些特定行的背景顏色,更準確地說是從data函數中更改背景顏色。

QVariant CCustomModel::data(const QModelIndex &index, int role) const 
{ 
    if (role == Qt::DisplayRole) 
    { 

    switch (index.column()) 
    { 
     case colName:   return QVariant(QString::number(1)); 
     case colAdress:  return QVariant(QString::number(2)); 
     case colGender:  return QVariant(QString::number(3)); 
     case colTelephone: return QVariant(QString::number(4)); 
     default: 
     return QVariant(); 
    } 
    } 

    if(role == Qt::BackgroundColorRole) //also tried Qt::BackgroundRole and Qt::ForegroundRole 
    { 
    return QVariant(QColor(Qt::red)); 
    } 
    return QVariant(); 
} 

這很簡單,無法正常工作。數字顯示,但背景顏色仍然是最基本的。這裏有沒有可能的解決方案?

+0

你以某種方式限制其從模型中所要求的角色?代碼是否真的到達聲明並且不會畫紅色?或者你永遠不會得到角色'BackgroundColorRole'的請求? – Hayt

+0

我經過測試,總是得到該角色的請求。我對標誌有限制,不能選擇或編輯,但我不是這個問題。 – student

+0

另外如果我使用return QVariant(QColor(Qt :: red));除了角色檢查之外,我在每個單元格中都會收到一個小紅色方塊和旁邊的數字,但就是這樣。 – student

回答

0

試試這個:

if(role == Qt::BackgroundRole) 
    { 
     return QBrush(QColor(Qt::red)); 
    }