Why is it more efficient to remove a QGraphicsItem from its scene before destroying it?
Asked Answered
K

1

10

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.

Klump answered 2/5, 2012 at 20:56 Comment(0)
J
6

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.

Jukebox answered 2/5, 2012 at 21:4 Comment(2)
Thanks for that. I checked the source again and there actually is a line that checks if the scene exists, and if so, calls d_ptr->scene->d_func()->removeItemHelper(this);. I guess that must be it. So it seems you're right, that the note might just be a bit misleading (either that or I'm a doofus).Klump
@Anthony: I'm going to just go with misleading :-) . Docs are meant to be helpful, and if it was confusing to you, then its a valid observation. Good job on checking through the source to confirm.Jukebox

© 2022 - 2024 — McMap. All rights reserved.