8
votes

What I should to do to delete QGraphicsItem?

To remove item from the scene I use

 QGraphicsScene::removeItem(QGraphicsItem * item);

From the docs for this method:

i.e., QGraphicsScene will no longer delete item when destroyed

So I see only one way:

delete item;

But may be another? For example for QWidget is able to set attribute

setAttribute( Qt::WA_DeleteOnClose );

That causes to deleting of the object. May be there is something similar for QGraphicsItem?

2
Item is as base class for all items in QGraphics Scene. As it is not derived from a QObject or a QWidget, I believe that the correct way of deleting it (after removing it from a scene) is just to call delete item;Martin Prazak
item->deleteLater()ratchet freak
@martin_pr Or you can use QGraphicsObject.thuga
@ratchetfreak - there is nothing confusing about this, deleteLater() is intended to safely delete objects, which are connected to event loops, so that deletion occurs after all events are processed. If there is no event loop there is no need to use deleteLater() nor is it possible absent the event loop, so you just delete.dtech
@martin_pr Yes, but you'll be only deriving from one class :Pthuga

2 Answers

10
votes

Unfortunately, QGraphicsItem is a base class of all graphics items usable inside QGraphicsScene, and, as most "item-like" objects in Qt, is not derived from QWidget or QObject. Moreover, they can only be parented to another QGraphicsItem (apart from being owned by QGraphicsScene.

After removing an item from a scene, unless it is parented to another QGraphicsItem, Qt expects the programmer to delete it manually by calling delete item; explicitly (or to use a smart pointer to manage the lifetime of the item after it was removed).

0
votes

It seems the issue lasting for long time today and there are open bugs also.

But it seems to have a workaround, which I could find it useful and after hours of debugging and reading and investigations I have found it here:

https://forum.qt.io/topic/71316/qgraphicsscenefinditembsptreevisitor-visit-crashes-due-to-an-obsolete-paintevent-after-qgraphicsscene-removeitem/17

Some other tips and tricks regarding Graphics Scene here: https://tech-artists.org/t/qt-properly-removing-qgraphicitems/3063/6