0

I want to set background color for selected row from my listview model.After select another row,the color of previous row is make transparent.Thanks!

    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
paulc
  • 125
  • 6

1 Answers1

0

You need to track a selection thought selection model of your view. When selection is modified, you may set data to your model. For example: model->setData( selectedIndex, QBrush(Qt::red), Qt::BackgroundColorRole );

You should understand, that one model may be assigned to several views. For deep understanding I suggest you to read about model-view programming in qt.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
  • auto sel = lst->selectionModel()->selectedIndexes(); QModelIndex firstSel = sel.at(0);Mymodel()->setData(firstSel, QBrush(Qt::yellow), Qt::BackgroundColorRole); doesn't work – paulc Jun 15 '16 at 07:43
  • @paulc what is your `Mymodel()`? Show an SSCCE, or your `setData` implementation. What base class for your model do you use? – Dmitry Sazonov Jun 15 '16 at 07:53