According to the QGraphicsItem destructor documentation, "It is more efficient to remove the item from the QGraphicsScene before destroying the item."
Why is that? I can't think of how it could make a difference. And if it did make a difference, shouldn't the QGraphicsItem destructor just call:
if (scene() != NULL)
scene()->removeItem(this);
I checked the source, and this does not seem to be the case, although sometimes I have a tough time understanding Qt source. EDIT: See comments in jdi's answer.
Maybe I am interpreting the docs differently than you (I have not looked at the source):
QGraphicsItem::~QGraphicsItem () [virtual]
Destroys the QGraphicsItem and all its children. If this item is currently associated with a scene, the item will be removed from the scene before it is deleted.
Note: It is more efficient to remove the item from the QGraphicsScene before destroying the item.
I take that to mean it will remove it from the scene first before destroying because that is more efficient. But if you say the source does not indicate anywhere that this occurs, then is seems the docs would be false?
If I had to take a guess as to why it would be more efficient to remove the item first before destroying it (regardless of whether the API really does it for you in the destructor), I would think it would have to do with what triggers the scene to reindex. Maybe by deleting an item that is still in the scene, the cascading deletions of child items would constantly trigger the scene to reindex. Whereas, if you were to remove the item first, it may efficiently pull out the entire hierarchy in a way that only requires a single update of the scene, and then the normal deletion can occur without further affecting it? There may even be more cascading effects of other child events/signals while they are deleted within the scene.
I'm betting the logic behind the "Note" is to inform those who would subclass a QGraphicsItem and overload the destructor to keep in mind the need to remove from the scene first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With