I should start by a disclaimer that I’m neither a C++ or Qt expert, there may be better or elegant ways to do it and I have found this implementation is more straightforward than digging in TreeView’s QML source code.

So we have a small problem, the TreeView in QML doesn’t provide any way to expand or collapse items. Alright, what would be the best way to tackle this? Let’s look at the available options at our hands:

  • TreeView QML provides the following methods:
    • expand (QModelIndex)
    • collapse (…)
    • others …

And then we have implemented the AbstractItemModel. If you sit for a moment and think we can actually aggregate new methods to our AbstractItemModel with Q_INVOKABLE and call them in our QML code.

So we will implement a new method called getChildrenIndexes (that of course is sort of a bad name when I think about it).

QVariantList GenericModel::getChildrenIndexes()
{
    QVariantList indexes;
    GenericNode *parent = rootItem->child(0)->parent();

    for(int i = 0; i != parent->childCount(); ++i) {
        GenericNode *child = parent->child(i);
        indexes.push_back(createIndex(i,0, reinterpret_cast<quintptr>(child)));
    }

    //reinterpret_cast<quintptr>(c) ( found in inners of QModelIndex)



    return indexes;

}

Then put the Q_INVOKABLE QVariantList getChildrenIndexes(); in your model header.

In our QML code it will go like this:

                onAssignSubscriptionModel: {
                    treeView.model = model; // TODO: throw a WorkerScript at it. 
                    var someIndexes = treeView.model.getChildrenIndexes();
                    console.log(someIndexes); // Our QVariantList gets converted to an array
                    for(var i = 0; i <= someIndexes.length - 1; i++) {
                        treeView.expand(someIndexes[i]);
                        //console.log(treeView.isExpanded(itemIndex));
                    }
                    someIndexes = undefined; // not sure if effective but I want it garbage collected afterwards. 

                }

After that? Your items should be automatically expanded. Note that this is an expensive process, it’s not much about creating the indexes but more that it will tax the QML engine side if you have a lot of items. At the same time I’d like to say that I did go through it with around 13k items in my database and didn’t notice any slow down, keep your eyes open though.

A quick summary? We got the indexes of our top-level items. Do remember that the root item is always invisible. Which brings me to

remember to adapt this to whatever node structure or container you have nobody should expect rootItem->child(0)->parent(); line in anyone’s AbstractItemModel meaning, you probably don’t have a child or parent method, maybe.