How to display correctly Treeview with QML Qt 5.5

kavaliero picture kavaliero · Oct 9, 2015 · Viewed 9.2k times · Source

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 the moment I got something like that :

    TreeView {
        id:listTree
        anchors.fill: parent
        anchors.leftMargin: 1
        headerVisible: false
        backgroundVisible: false

        selection: ItemSelectionModel {
            model: myModel
        }
        TableViewColumn {
            role: "name"
        }

        itemDelegate: Item {
            Text {
                anchors.verticalCenter: parent.verticalCenter
                color: styleData.textColor
                elide: styleData.elideMode
                text: styleData.value
            }
        }

        Component.onCompleted: {
            model.append({"name":"Never"})
            model.append({"name":"gonna"})
            model.append({"name":"give"})
            model.append({"name":"you"})
            model.append({"name":"up"})
            model.append({"name":"Never"})
            model.append({"name":"gonna"})
            model.append({"name":"let"})
            model.append({"name":"you"})
            model.append({"name":"dow"})
        }
    }

enter image description here

And I would like something like that :

enter image description here

How can I do it ?

Answer

cmmuf34e79d5761dcd picture cmmuf34e79d5761dcd · Jan 16, 2016

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);
}