PDA

View Full Version : Correctly deleting a qwidget with no parent



boblatino
26th July 2010, 23:15
In my application I have a class that creates a widget with no parent and I want to destroy (call close() and it will automaticaly delete the object by seting the appropiate flag) when it looses the focus. The problem is that if I call the close function in the looseFocus event of the widget, the pointer in my creator class remains valid. I have seen the destroyed signal for QObject that I could use to invalidate the pointer once the widget has been destroyed. As this should be a normal use case I need to know if this is the correct approach to go.

1) loose focus
2) call close
3) wait for the destroyed signal in the creator class
4) invalidate the pointer in the creator class


Thanks
Ramiro

Lykurg
26th July 2010, 23:21
Calling close does not free the memory you also have to delete it or set the Qt::WA_DeleteOnClose flag. The problem with the pointer can be solved by using QPointer.

But it seems not right to me. I would emit a signal, when the widget looses its focus and handle all deleting stuff in the "creator class".

boblatino
26th July 2010, 23:30
I would emit a signal, when the widget looses its focus and handle all deleting stuff in the "creator class".

Thanks Lykurg, The only thing Im thinking with that approach is that the code will emit a signal (if its connected as a direct call) it will call close and then delete (but currently the thread is inside the class that is being deleted due to the emit direct call. I have done a test with that and changing the direct to queued mode solved the problem but I want to know if this is the correct way of doing it.


Thanks
Ramiro

franz
27th July 2010, 06:01
Use QObject::deleteLater(), which is practically the same as setting WA_DeleteOnClose, with the difference that the creating class tells the object to delete itself when done, instead of telling it to delete itself in a while.