Is there a native data model from TreeView in QML?

烈酒焚心 提交于 2020-02-23 04:12:57

问题


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?


回答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
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/43515545/is-there-a-native-data-model-from-treeview-in-qml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!