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.

    Now when I click the [x] to close one of those the windows, the item deletes itself from the model, however since I do not interact with the ItemModel/ItemView directly I don't know where to call beginRemoveRows() endRemoveRows().

    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:

    AbstractPlot::~AbstractPlot()
    {   
        // 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) {
                    m_parent_item->eraseChild(c);
                }
            }
        }
        // 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

    Hi,

    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?

    EDIT:

    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()
    {
        endRemoveRows();
    }
    

    The destructor of the item now loks like this

    TreeItem::~TreeItem()
    {
        emit signalBeginRemoveItem(static_cast<TreeItem*>(this));
        if(getParentItem() != NULL)
        {
            getParentItem()->eraseChild(this);
        }
        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 ?


Log in to reply
 

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