如何完全遍历QStandardItemModel? [英] How to iterate through a QStandardItemModel completely?

查看:1926
本文介绍了如何完全遍历QStandardItemModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个QStandardItemModel,它显示在q QTreeView中.效果很好.

I have a QStandardItemModel, which I display in q QTreeView. Works fine.

要突出显示相关行,我要突出显示其中一些行:因此,我有一个QStringList,其中要突出显示QStandItem *的名称.

To highlight relevant rows I want to highlight some of them: Therefore I have a QStringList with the names of the QStandItem* s to be highlighted.

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);
        }
    }
}

我的模型具有以下结构:
Level_1
+->等级11
+->等级12
+->等级13
级别_2
+->等级21
+-> Level_22
+->等级23
...

My Model has following structure:
Level_1
+--> Level_11
+--> Level_12
+--> Level_13
Level_2
+--> Level_21
+--> Level_22
+--> Level_23
...

在这里,迭代11、12和13级的谷,然后停止.

Here, it iterates trough Levels 11, 12 and 13 then it stops.

推荐答案

我希望它可以为您提供帮助:

I hope it helps you:

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);

这篇关于如何完全遍历QStandardItemModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆