View Full Version : QObject::destroy() - ensure that the destruction is done before processing the signal

4th November 2011, 12:57
Hello There,

My question is pretty simple:
How is it possible to ensure that an actual QObject is destroyed? Connecting to QObject::destroyed() does not guarantee that the destruction is already done and I could not find any call anywhere to wait until it is done (I was thinking on QCoreApplication::processEvents() or QObject::sender() set to 0 but none of those work).
So, how to do that?

(If interested why:
In practice the sender object is a QThread what calls deleteLater() and quit() when it is finished. The slot connected to its destroy() signal - what is emitted by Qt just after the ~ destructor runs - sometimes invoked earlier than the destruction of the object (QObject/QThread or their subclasses) is actually done. It is clear since for example if a QCoreApplication::quit() is called from the slot then it sometimes (sometimes not) results in a "QThread: Destroyed while thread is still running". That also makes it quite difficult to reuse certain pointers.)

Cheers :)

5th November 2011, 04:36
A QObject emits QObject::destroyed(), as the docs say:

This signal is emitted immediately before the object obj is destroyed, and can not be blocked.
(emphasis mine). The object doesn't exist after the destructor is run, so it clearly cannot emit anything, and even if it could the sender() would be invalid... leading quickly to crash city.

The problem you are trying to solve sounds like you want a way to ensure threads are stopped before exiting the application. Perhaps connect something to QCoreApplication::aboutToQuit() and do your thread cleanup there?

8th September 2015, 17:05

Set this attibute to your QWidget and then you can catch the signal destroyed() when close button is clicked: