Nominate our 2022 Qt Champions!

Expanding some branches of a treeview

  • Hi All,
    in my code I produce a then push it onto a tree view as below

    //your code here
        QStandardItemModel tree_model;
    //your code here
        QStandardItem* item;
        for( unsigned int i = 0; i < score.win_element_list.size( ); i++ )
            if( ( int ) i ).data_a > current_level )
                 sub_level = 0;
                 level_number = QString::number( current_level );
                    QString level = "level " + level_number;
                    item = new QStandardItem( QString( level ) );
                    QString wording = "Element\t\t";
                    wording += QString::number( sub_level );
                    QStandardItem* function = new QStandardItem( QString( wording ));
                    item->appendRow( function );
    then at end I use
    tree_model.setItem( column, 0, item);

    which produces the tree as needed.
    However when I call this draw function ( after I've added new elements ect ) I lose all the expanded branches of my tree. However I've stored if a branch is expanded as a variable. Is there some way I can step through treeview or QStandardItemModel. I've check the documents and can see QTreeView::setExpanded but I can't work out how to get QModelIndex from treeview or QStandardItemModel. Can anyone advise please? Thanks

  • Lifetime Qt Champion

    Im not 100% sure what question is, but you can use index (in the model) function to get QModelIndex.
    This function will expand a parent and all sub.childs.

    void MainWindow::expandNode(const QModelIndex &parentIndex, bool expand) {
      tree->setExpanded(parentIndex, expand);
      for (qint32 rowNum = 0; rowNum < treeModel->rowCount(parentIndex); ++rowNum) {
        QModelIndex childIndex = treeModel->index(rowNum, 0, parentIndex);
        tree->setExpanded(childIndex, expand);

Log in to reply