Qt,QListView模型

时间:2016-06-14 21:14:41

标签: c++ qt qlistview qabstractitemview

我想从listview模型中为所选行设置背景颜色。选择另一行后,前一行的颜色变为透明。谢谢!

    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

1 个答案:

答案 0 :(得分:0)

您需要跟踪视图的selection model选择。修改选择后,您可以将数据设置为模型。例如:model->setData( selectedIndex, QBrush(Qt::red), Qt::BackgroundColorRole );

您应该了解,可以将一个模型分配给多个视图。为了深刻理解,我建议您阅读model-view programming in qt