Search code examples
c++qtmemory-managementqwidget

Deleting object that inherits from QWidget, WA_DeleteOnClose segmentation fault


I'm using an object the inherits QWidget, and in order to know when it is closed, I've used setAttribute(Qt::WA_DeleteOnClose), and connected

connect(myObj,SIGNAL(destroyed(QObject*)),this,SLOT(handleFinish()));

However, when the object is being deleted, I get munmap_chunk(): invalid pointer, and when I look at the address of the pointer, it is one of the data members of myObj, which is really not a pointer.

I allocate myObj dynamically, so it is supposed to be on the heap - myObj = new myObj(); The error comes at the end of myObj destructor, and I've checked that this is the first time the destructor is called (after looking at When setting the WA_DeleteOnClose attribute on a Qt MainWindow, the program crashes when deleting the ui pointer).

Any suggestions for dealing with it?


Solution

  • By the time you receive the destroyed signal, the object is only a QObject - not a QWidget and definitely not of any derived type. You can only access the members and methods provided via QObject, not via any other type.

    It seems that you wish to be notified when a widget is about to close: for that, install an event filter that intercepts QEvent::close on the widget. See also this answer and a discussion of why a closeEvent cannot be generally handled via a slot.