Search code examples
qtqtreeview

How to show all the children items in QTreeView?


I tried to create a QTreeView as example from Qt

http://doc.qt.io/qt-5/qtwidgets-itemviews-editabletreemodel-example.html

enter image description here

When we click on the triangle before each "parent" item, the "children" items will be shown.

In my case I add this line to tree view

 myTreeView->setRootIsDecorated(false);

As the result, there is no more triangle before each "parent" item.

enter image description here

But the "children" items are also not shown any more.

My requirements are:

  • disable the triangle before each "parent" item
  • show ALL items in the tree, both "parent" and "children"

How can I do it?


Solution

  • As per the comment you can programmatically ensure all items in the tree are visible by calling QTreeView::expandAll...

    myTreeView->expandAll();
    

    Note that it may need to be called again as/when child items are added to the model which, depending on the size of the model, could become a performance bottleneck.

    As an alternative, it might be better to inherit from QTreeView and override the QTreeView::rowsInserted member.

    virtual void MyTreeView::rowsInserted (const QModelIndex &parent, int start, int end) override
      {
    
        /*
         * Let the base class do what it has to.
         */
        QTreeView::rowsInserted(parent, start, end);
    
        /*
         * Make sure the parent model index is expanded.  If it already
         * is expanded then the following should just be a noop.
         */
        expand(parent);
      }
    

    This should give better performance for large models.