How to display correctly Treeview with QML Qt 5.5

后端 未结 2 1495
醉话见心
醉话见心 2021-01-13 02:21

I\'m trying to create a correct Treeview with Qml Qt 5.5. I succeed to have a Treeview with a global root. But impossible to find how to add child for row item.

For

相关标签:
2条回答
  • 2021-01-13 02:28

    Your model doesn't have any parent child relationships which is why its displayed like a list.

    You'll want your "TreeModel" to be a collection of TreeItems. Each TreeItem will have knowledge of their own children and their parent item.

    You can follow a fully implemented Qt example found here http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html. You'll want to (in C++) make a class for TreeItem, and a separate class for your TreeModel.

    That example is working code, you can just copy and paste it and get a working model for your TreeView.

    The part you'll be particularly interested in is the implementation of the method setupModelData(). That's where you'll want to parse through your wonderful dataset of 80's lyrics and assign each of them a TreeItem.

    Each TreeItem (one for every row of data) should be given knowledge of its parent upon creation (in its constructor). Then as soon as its children are created, call parentTreeItem.appendChild(childTreeItem)

    When your model is completed, you can assign it to your qml view in a few ways, registering it with qmlRegisterType is what I prefer (http://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterType)

    Once registered, it can be created in qml as though it were a ListView or any other qml object.

    NOTE: You'll have this rootItem. This is something that isn't usable by the view, but all your "first indentation" parents are children of the rootItem.

    Good luck!

    Can you provide a code snippet of what line is causing your about failing to make a shortcut for QAbstractItemModel?

    0 讨论(0)
  • 2021-01-13 02:36

    You can also create a TreeModel class that extends QStandardItemModel and overrides roleNames(), like done here. To add children to nodes in your tree, just use appendRow().

    TreeModel::TreeModel(QObject *parent) : QStandardItemModel(parent)
    {
        QStandardItem *root = new QStandardItem("root");
        QStandardItem *child = new QStandardItem("child");
        this->appendRow(root);
        root->appendRow(child);
    }
    
    0 讨论(0)
提交回复
热议问题