Important: Please read the Qt Code of Conduct -

[Solved] beginRemoveRows() with an unknown amount of rows

  • I have a custom subclass of QAbstractItemModel which I use for my QTreeView. I want to remove a (root) item of the tree. Therefore I call delete rootItem;. As this modifies the model data I would have to wrap that call inside of beginRemoveRows() and endRemoveRows(). However, inside the destructor of the rootItem all children will be deleted recursively. Therefore, I don't know how many items will be removed (nor do I know the parent) and therefore I don't know which parameters I have to pass to beginRemoveRows().

    How do I solve this issue?

  • Moderators

    You shouldn't remove the root. Root is the invisible item that all the top level items are children of.

    If you want to remove a single item( with QModeIndex index) from its parent (index.parent()) then you call beginRemoveRows(index.parent(), index.row(), index.row()) i.e. you remove a single row. Children of the index that is removed is not counted here.

  • @Chris-Kawa Sorry for being unclear. I don't want to remove the invisible root item but one of the top level items (a root item for the user, one with no parent).
    Anyway, this doesn't really matter in my case. When I want to delete any item in my tree then it will automatically delete all it's children recursively in its destructor, no matter on which level it is. So I don't want to remove a single either either.

    Deleting all the children in an items destructor is working, all I need to know is figure out what to pass to beginRemoveRows() before calling delete on the "parent item".

  • Moderators

    That's what I'm saying. If you wan't to remove an item you don't have to worry about its children - you don't have to consider them at all in the call to beginRemoveRows().

    Lets say you have this tree:


    and lets say you want to remove "item2" with all children. This is how to do it:

    QModelIndex index = /*  get the index of "item2"  */
    beginRemoveRows(index.parent(), index.row(), index.row());
    ...// physically remove the item from your data structure along with all the children

  • @Chris-Kawa Oh, now i understand. Well, this makes a lot of sense.

    Thank you for your help, very appreciated!

Log in to reply