HowTo find Subitem in QAbstractItemModel and QTreeView class?

Question: how to find sub item, in a QTreeView loaded QAbstractItemModel model with model->match() method?

Problem: model->match() can't find sub items, wtf?!

Here is the example:

alt text http://www.freeimagehosting.net/uploads/179eee87e3.png

As you can see from the picture, I'm trying to expand Layouts sub item with this code:

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

Where settings.ini file contains:

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

PS: root items successfully expands on start!

Answers


Here is the solution:

QModelIndexList Items = model->match(
            model->index(0, 0),
            Qt::DisplayRole,
            QVariant::fromValue(item),
            2, // look *
            Qt::MatchRecursive); // look *
  • * Without that argument match() function searches only 1 level

My working example on 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
}

Need Your Help

python setup.py egg_info mysqlclient

python macos python-3.x mysql-python macos-sierra

Trying to install mysqlclient using pip3 on Python 3.6.0

org.hibernate.MappingException: Unknown entity:

java hibernate spring

I really want to understand what is going on with my code.