簡體   English   中英

Qt,QListView模型

[英]Qt,QListView Model

我要為列表視圖模型中的選定行設置背景色。選擇另一行后,上一行的顏色變為透明。謝謝!

    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

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

您應該理解,一個模型可以分配給多個視圖。 為了深入理解,建議您閱讀qt中的模型視圖編程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM