When setting the WA_DeleteOnClose attribute in Qt MainWindow, the program crashes when the ui pointer is deleted

I set the WA_DeleteOnClose widget WA_DeleteOnClose to MainWindow.

 setAttribute(Qt::WA_DeleteOnClose); 

However, when I close this main window, I get segfault in its destructor, which has only delete ui;

In short, by creating a Qt4 GUI application in Creator by adding the setAttribute(Qt::WA_DeleteOnClose); constructor setAttribute(Qt::WA_DeleteOnClose); to the constructor, the program now crashes on exit.

+7
c ++ segmentation-fault qt qt4
source share
2 answers

Do you get segfault in your destructor the first time or the second time? Remember that your main window destructor should only start once. In other words, it should start either due to a stack break, or because of WA_DeleteOnClose , and not both.

IIRC, the creator will push the main window onto the main() stack. Therefore, when main() returns the main window, it will be destroyed.

+10
source share

this link gives a good suggestion for a solution.

I believe that it is best to define a QPointer to point to an object, and check for NULL each time, so when the UI object is destroyed, the pointer is set to NULL directly. "QPointer provides protected pointers for QObjects. You can use it to store a link to your dialog box, and when the dialog box is deleted, the pointer will automatically be set to NULL."

0
source share

All Articles