简体   繁体   English

Qt,QListView模型

[英]Qt,QListView Model

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

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 ); 例如: 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 . 为了深入理解,建议您阅读qt中的模型视图编程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM