How to delete all QGraphicsItem from QGraphicsScene

Donotalo picture Donotalo · Sep 15, 2011 · Viewed 14.9k times · Source

I've written a derived class from QGraphicsScene. At a point I need to remove all items from the scene and I want the items to be physically destroyed (destructor called). I tried the following:

QList<QGraphicsItem*> all = items();
for (int i = 0; i < all.size(); i++)
{
    QGraphicsItem *gi = all[i];
    removeItem(gi);
    delete gi; // warning at this line
}

Qt Creator emits a warning: warning: C4150: deletion of pointer to incomplete type 'QGraphicsItem'; no destructor called

I'm not sure why is that. QGraphicsItem has virtual destructor so the items should be deleted from memory.

If this is not the right way, how can I delete all QGraphicsItems from QGraphicsScene? Note that I know when the scene is deleted, all items will also be deleted. But i want to remove items from scene and draw other items. I want the removed items to be deleted from memory.

Answer

alexisdm picture alexisdm · Sep 15, 2011

You can remove and delete all items with QGraphicsScene::clear().