2
votes

The QT document had implied that any implementation of QAbstractItemModel can be used for TreeView.

These models are usually in C++, which is inconvenient for now.

So is there an native QML model which can be utilized in treeview?

Can I set a QStandardItemModel model from C++, and use this model in qml?

2
Not that I know of. But maybe this helps you: stackoverflow.com/a/33505913/2056452 (Especially the link to the documentation example) Also keep the comment to it in mind.derM
For now QML doesn'thave native tree model, you need to implement it by yourself using QStandardItemModel. Here is simple example how to do that.folibis

2 Answers

1
votes

The QStandardItemModel reference gives an example of how to use it for a TreeView:

QStandardItemModel model;
QStandardItem *parentItem = model.invisibleRootItem();
for (int i = 0; i < 4; ++i) {
    QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
    parentItem->appendRow(item);
    parentItem = item;
}

Next to this you can add the model to QML with the following:

view.rootContext.setContextProperty("treeViewModel", model);

You also need the root item from the model to show everything in the Treeview:

view.rootContext.setContextProperty("root", model.indexFromItem(model.invisibleRootItem()));

Now you can add it to you QML TreeView like follows:

  TreeView{
    model: treeViewModel
    rootItem: root

    TableViewColumn {
        role: "display" // is role 0
    }
}
1
votes

So is there an native QML model which can be utilized in treeview?

Still "no" in 2018.The current QML TreeView examples are still readonly static C++ models which require a lot of manual coding to use them for anything dynamic.

I found two nice pure QML examples for custom made tree views that use QML ListModel and Javascript arrays, e.g:

1) Youtube - TreeView component in pure Qt Quick https://gist.github.com/pcdummy/c03845aa9449168b7d24c491ad913fce

2) QMLRearrangeableTreeView from Eric Gregory which showcases drag&drop. I extended it to make it editable, and save/load the structure via a JSON string: QMLRearrangeableTreeView for edit&save