2016-06-14 21 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);

1つのモデルを複数のビューに割り当てることができます。深い理解のために、私はあなたが約model-view programming in qtを読むことをお勧めします。

+0

auto sel = lst-> selectionModel() - > selectedIndexes(); QModelIndex firstSel = sel.at(0); Mymodel() - > setData(firstSel、QBrush(Qt :: yellow)、Qt :: BackgroundColorRole); does not work – paulc

+0

@paulcあなたの 'Mymodel()'は何ですか? SSCCEまたは 'setData'実装を表示します。あなたのモデルの基本クラスは何ですか? –

+0

@paulcはコメントにありません - http://stackoverflow.com/help/how-to-ask –

関連する問題