PDA

View Full Version : Best way for a graphicsitem to delete itself



pherthyl
20th June 2008, 20:53
I have some graphicsitems that need to delete themselves once they're no longer needed. Right now I have a fadeTo(float) function, which will set up an animation to fade the item to a particular opacity value.
If I go item->fadeTo(0), it will fade to transparent and then delete itself, like so:



void SongItem::onAnimationFinished() {
onAnimationValueChanged(1.0);
animationTimeline->disconnect(this);
if(!opacity)
delete this;
}


That function is hooked up to the finished() signal of the timeline.

So my question is: Is having an item delete itself in a slot safe? If not, what's the best way to do it?

Thanks,
leo

marcel
20th June 2008, 21:32
You could implement a simple garbage collector in a subclassed graphics view.
Create a base graphics item from which you will inherit all your items. This should have a boolean flag that you set to true when the item is no longer needed.

Next, add a timer to the view that triggers once every 3 or 5 seconds. When it triggers, look at all the items and delete the ones that are not necessary.

Another way would be to not use a flag in the item, but instead keep a list of items to be deleted in the view and make the items add themselves to the list when they are no longer needed.

marcel
20th June 2008, 21:51
Actually, I think it is better to have the garbage collector in the scene, not the view, because you can have many views for the same items and it could get messy.

pherthyl
20th June 2008, 22:08
Just to clarify, the code I have does seem to work, (items delete themselves). The only concern I have is if I'm creating a race condition or something. I did have one random crash once and am concerned that it might have been caused by that.

Garbage collector is an option too, or perhaps emitting a signal to get the scene to delete the item (queuedconnection of course).

marcel
20th June 2008, 22:19
The only concern I have is if I'm creating a race condition or something. I did have one random crash once and am concerned that it might have been caused by that.
yes, that is the reason.



Garbage collector is an option too, or perhaps emitting a signal to get the scene to delete the item (queuedconnection of course).

I just thought a garbage collector would be more elegant... Queued connections are designed more for inter-thread communications. But I guess they could work... If not, you can always use postEvent.

pherthyl
20th June 2008, 22:59
Thanks. I'll give the garbage collector a try.

elcuco
21st June 2008, 11:18
How about QObject::deleteLater() ...?

pherthyl
22nd June 2008, 05:57
Bingo. Thanks elcuco, I vaguely remembered such a function existing, but couldn't find it anymore.