如何完全遍历QStandardItemModel

How to iterate through a QStandardItemModel completely?

本文关键字:QStandardItemModel 遍历 何完全      更新时间:2023-10-16

我有一个QStandardItemModel,我在QTreeView中显示它。没问题。

为了突出显示相关的行,我想突出显示其中的一些:因此,我有一个QStringList,其中包含要突出显示的QStandItem* s的名称。

QStringList namesToBeHighlighted = getNames();
QModelIndex in = myModel->index(0, 0);
if ( in.isValid() ) {
    for (int curIndex = 0; curIndex < myModel->rowCount(in); ++curIndex) {
        QModelIndex si = myModel->index(curIndex, 0, in);
        QStandardItem *curItem = myModel->itemFromIndex(si);
        if (curItem) {
           QString curItemName = curItem->text();
           if ( namesToBeHighlighted.contains(curItem->text()) ) {
               curItem->setFont(highlightFont);
           }
           else curItem->setFont(unHighlightFont);
        }
    }
}

My Model的结构如下:

Level_1+ - - -> Level_11
+ - - -> Level_12
+ - - -> Level_13
Level_2
+ - - -> Level_21
+ - - -> Level_22
+ - - -> Level_23

在这里,它遍历第11、12和13层,然后停止。

希望对你有所帮助:

void forEach(QAbstractItemModel* model, QModelIndex parent = QModelIndex()) {
    for(int r = 0; r < model->rowCount(parent); ++r) {
        QModelIndex index = model->index(r, 0, parent);
        QVariant name = model->data(index);
        qDebug() << name;
        // here is your applicable code
        if( model->hasChildren(index) ) {
            forEach(model, index);
        }
    }
}
QStandardItemModel model;
    QStandardItem* parentItem = model.invisibleRootItem();
    for (int i = 0; i < 4; ++i) {
        QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
        for (int j = 0; j < 5; ++j) {
            item->appendRow(new QStandardItem(QString("item %0%1").arg(i).arg(j)));
        }
        parentItem->appendRow(item);
        parentItem = item;
    }
forEach(&model);
相关文章:
  • 没有找到相关文章