15

问题:如何在带有方法的QTreeView加载QAbstractItemModel模型中找到子项目model->match()

问题model->match()找不到子项目,wtf?!

这是示例:

替代文字

从图片中可以看出,我正在尝试Layouts使用以下代码扩展子项:

void Dialog::restoreState(void)
{
    // get list
    QSettings settings("settings.ini", QSettings::IniFormat);
    settings.beginGroup("MainWindow");
    QStringList List = settings.value("ExpandedItems").toStringList();
    settings.endGroup();

    foreach (QString item, List)
    {
        if (item.contains('|'))
            item = item.split('|').last();
        // search `item` text in model
        QModelIndexList Items = model->match(model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(item));
        if (!Items.isEmpty())
        {
            // Information: with this code, expands ONLY first level in QTreeView
            view->setExpanded(Items.first(), true);
        }
    }
}

其中settings.ini文件包含:

[MainWindow]
ExpandedItems=Using Containers, Connection Editing Mode, Form Editing Mode, Form Editing Mode|Layouts

PS:根项目在启动时成功扩展!

4

2 回答 2

27

这是解决方案:

QModelIndexList Items = model->match(
            model->index(0, 0),
            Qt::DisplayRole,
            QVariant::fromValue(item),
            2, // look *
            Qt::MatchRecursive); // look *
  • *没有那个参数 match() 函数只搜索 1 级
于 2010-07-22T09:04:48.723 回答
0

我在 QTreeView 上的工作示例。

QModelIndexList Indexes = this->ui->treeView->selectionModel()->selectedIndexes();
if(Indexes.count() > 0)
{
    QStandardItemModel *am = (QStandardItemModel*)this->ui->treeView->model();

    QStack<QModelIndex> mis;
    QModelIndex mi = Indexes.at(0);
    while(mi.isValid())
    {
        mis.push(mi);
        mi = mi.parent();
    }

    QStandardItem *si;
    bool FirstTime = true;
    while (!mis.isEmpty())
    {
        mi = mis.pop();
        if(FirstTime)
        {
            FirstTime = false;
            si = am->item(mi.row());
        }
        else
        {
            si = si->child(mi.row());
        }
    }
  // "si" - is selected item
}
于 2012-03-26T15:06:50.450 回答