问题
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