2

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?

jpnurmi
  • 5,716
  • 2
  • 21
  • 37
My_Cat_Jessica
  • 123
  • 1
  • 11
  • Not that I know of. But maybe this helps you: http://stackoverflow.com/a/33505913/2056452 (Especially the link to the [documentation example](http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html)) Also keep the comment to it in mind. – derM - not here for BOT dreams Apr 20 '17 at 12:16
  • 1
    For now QML doesn'thave native tree model, you need to implement it by yourself using `QStandardItemModel`. [Here](http://stackoverflow.com/documentation/qml/2254/integration-with-c/23180/creating-a-simple-model-for-treeview#t=201704201822433178982) is simple example how to do that. – folibis Apr 20 '17 at 18:24

3 Answers3

1

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
    }
}
Llamma
  • 43
  • 7
1

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

0

Qt doesn't ship with it, but.. after running across a number of half-answers, I finally found a how-to for a C++ class that then lets you populate and update from QML. No reason this couldn't become a trivial extension.

https://riptutorial.com/qml/example/23180/creating-a-simple-model-for-treeview

There doesn't seem to be an acccompanying git repo, but it's a fairly straightforward copy-pasta job, if you've already got a C++ main.

Kukulski
  • 96
  • 1
  • 5