Important: Please read the Qt Code of Conduct -

where to call beginRemoveRows() when QAbstractItemModel is deleted from somewhere else

  • Hello,

    I have a model view that derives from QAbstractItemModel.
    The items in the view are a list of open windows and derive from QMainWindow as well as my item class for the modelview.

    Any ideas?

  • @gde23 said in where to call beginRemoveRows() when QAbstractItemModel is deleted from somewhere else:

    the item deletes itself from the model

    How? Can you show the code?

  • @VRonin
    Thanks for the fast answer.
    Here is the destructor of the item:

        // remove item from parent-item (its a tree-model)
        if(m_parent_item != NULL)
            for(size_t c=0; c<m_parent_item->getChildCount(); c++) {
                if(m_parent_item->getChild(c) == this) {
        // delete other stuff

    the eraseChild() method just removes the child from the vector containing the child items

    void Item::eraseChild(const size_t index)
        m_child_items.erase(m_child_items.begin() + index);

  • Lifetime Qt Champion


    Is it me or are you children items responsible for their own deletion from their parents ?

  • Hi,

    yes. At the moment it's the children being responsible for this. When the child destructor is called the item deletes the entry from the parent, but maybe it's a bad idea to implement it that way?


    Ok i got it working somehow.

    I added two slots to the Model that have to be called from the item that wants to delete itself before it commits suicide.

    void MyModel::slotBeginRemoveItem(TreeItem* item)
        QModelIndex ind = pointer2ModelIndex(item);
        QModelIndex parent = ind.parent();
        beginRemoveRows(parent, ind.row(), ind.row());
    void MyModel::slotEndRemoveItem()

    The destructor of the item now loks like this

        emit signalBeginRemoveItem(static_cast<TreeItem*>(this));
        if(getParentItem() != NULL)
        emit signalEndRemoveItem();
        // other delete stuff

  • Lifetime Qt Champion

    Not a good idea indeed. Why would the item have to know anything about what stores it ?