2016-06-14 88 views
0

我想爲我的列表視圖模型中的選定行設置背景顏色。選擇另一行後,上一行的顏色變得透明。謝謝!Qt,QListView模型

QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { 
    if (role == Qt::DisplayRole) { 
     qDebug() << "get row:" << index.row(); 
     //auto sp = pets[index.row()].getSpecies(); 
     //return QString::fromStdString(sp); 
     string tara = v[index.row()].getTara(); 
     int pct = v[index.row()].getPct(); 
     QString linie; 
     linie.append(QString::fromStdString(tara)); 
     linie.append(" "); 
     linie.append(QString::number(pct)); 
     return linie; 
    } 
    if (role == Qt::BackgroundColorRole) 
    { 
      QBrush redBackground(Qt::red);//here ,i don't now to put a condition when row is selected 
      return redBackground; 
    } 

    return QVariant{}; 
} 
//here i try to brush the selected row 
QObject::connect(lst->selectionModel(), &QItemSelectionModel::selectionChanged, this, &Console::onSelectionChanged); 
void Console::onSelectionChanged() { 
auto sel = lst->selectionModel()->selectedIndexes(); 
QModelIndex firstSel = sel.at(0); 
Mymodel->setData(firstSel, QBrush(Qt::yellow), Qt::BackgroundColorRole); 
//Console is a class which inherits QWidget,here is a QListView* lst 
+0

可能,您需要查看代表:http://doc.qt.io/qt-5/qitemdelegate.html#paint。沒有確切的問題和一些SSCCE /屏幕截圖很難說。 –

+0

仍然看不到最終的'data'和'setData'實現。 –

+0

我沒有任何數據和setData的實現 – paulc

回答

0

您需要跟蹤您的視圖的選擇思想selection model。選擇修改後,您可以將數據設置爲您的模型。例如:model->setData(selectedIndex, QBrush(Qt::red), Qt::BackgroundColorRole);

您應該明白,可以將一個模型分配給多個視圖。爲了深入理解,我建議你閱讀model-view programming in qt

+0

auto sel = lst-> selectionModel() - > selectedIndexes(); QModelIndex firstSel = sel.at(0); Mymodel() - > setData(firstSel,QBrush(Qt :: yellow),Qt :: BackgroundColorRole);不起作用 – paulc

+0

@paulc你的'Mymodel()'是什麼?顯示一個SSCCE,或者你的'setData'實現。你使用什麼樣的基礎類? –

+0

@paulc不在評論 - http://stackoverflow.com/help/how-to-ask –