How to, inside a QTreeView, delete a selected row and all his children ?



  • I have a "Files_treeView" who is an implementation of my QTreeView,
    at delete time (after right click on an item and choose in a menu to remove the row), i try to remove the row concerned by the item selected and all his children. But i can not.

    here is what i try first:

    @
    QModelIndex index_selected = this->currentIndex();
    this->model->removeRow(index_selected.row(),index_selected);
    @

    "this->model" is my model point on the current model viewing on the tree.
    same result if i click on first column (i thank maybe it was the wrong item selected in the wrong column... but it is not this problem). I try to sibling the index in the column 0 concerned by the currentItem() selected... but no more.

    after i think about delete with:

    @
    this->model->removeRows(index_selected.row, the_childs, index_selected)
    @

    but how to know hw many children have the selected item (if i first sibling it on column 0) ?
    and is it the solution ?
    or what is the solution ?


  • Moderators

    First of all current item and selected items are not always the same thing. For example if multi-selection is enabled multiple items can be selected but only one can be current. Similarly if selection is disabled no item can be selected but there still will be current item. Also, depending on selection mode, current item and selected item can be two different items. So be mindful of these differences.

    If you really want to remove current item this will simply do:
    @
    //assuming "this" is the treeview
    auto idx = currentIndex();
    model()->removeRow(idx.row(), idx.parent());
    @
    If you on the other hand want to remove all the selected items here's how:
    @
    //assuming "this" is the treeview
    while(!selectionModel()->selectedIndexes().isEmpty()) {
    auto idx = selectionModel()->selectedIndexes().first();
    model()->removeRow(idx.row(), idx.parent());
    }

    //it's important to note that you can't just iterate through the selectedIndexes() because the indexes in it will be invalidated by the removal.
    @



  • thanks Chris Kawa, this help me to point my error and also to understand the difference between selected and current index.

    also, with your help, i find also the solution for delete the row and children also if i right click on an other column.
    (and also, i could sure do it for multi-selection too)
    like this:

    @
    QModelIndex index_current;
    index_current = this->model->sibling(this->currentIndex().row(),
    0,
    this->currentIndex() );
    this->model->removeRow(index_current
    index_current.parent() );
    @

    thanks again for your help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.