Important: Please read the Qt Code of Conduct -

How to dynamically add nodes to a QtreeView

  • 0.0.4 ,
    0.1.0 ,
    0.1.6 ,
    0.1.7 ,
    0.2.9 ,
    0.3.3 ,
    0.3.5 ,

    List = [A, [B,C,D,E], [a,b,c,d,e]

    The Tree to be created is as follows


    Now I want to create the nonleaf at the beginning. I want to add the leaf nodes leaf1, leaf2,leaf3 and leaf11, leaf22, leaf33 dynamically when I expand d and a. Can some write a sample code how to add dynamically add leaf nodes in QtreeView

    How can I use canfetchmore and fetch more

  • Moderators

    @Qt-Enthusiast I would just catch the void QTreeView::expanded(const QModelIndex &index) signal and add your items there.

    As for adding items in code, it works the same whether it's on expand or in the beginning. Here is an example using QStandardItems:

    auto model = new QStandardItemModel();
    auto tree = new QTreeView(this);
    // add items like so
    model->appendRow(new QStandardItem("leaf1"));

  • but my only question is

    I have QAbrtacItemModel and also expanded has to work only on
    small a and small d

  • Moderators

    @Qt-Enthusiast Ok so I used QStandardItemModel as an example, obviously adapt to your model. :)

    As for expanding only small "a" and "d", you add that to your expanded() function logic. You get the QModelIndex and then you can just check if it is the one you need to populate or not.. Something like:

    void MyWidget::somethingExpanded(const QModelIndex &index)
       if (myModel->myItemName(index) == "a" || myModel->myItemName(index) == "d")
           // add your items to your model here

Log in to reply