Solved QDialog attribute WA_DeleteOnClose
-
Hi,
In the main window, I call the MyDialog class that derives from QDialog class:// in MainWindow MyDialog *d = new MyDialog(); d->setAttribute(Qt::WA_DeleteOnClose); d->show();
By WA_DeleteOnClose attribute, I can delete MyDialog window, but the "d" pointer remains valid. How do I make sure that when I close the MyDialog the "d" pointer is deallocated?
Thanks
-
@Gianluca86 Hi there!
Qt::WA_DeleteOnClose
is made to delete the pointer when the widget is closed. If you manuallydelete d;
, the pointer won't be valid anymore -
Ok, I try to be more specific.
// in MainWindow if(d == NULL) { MyDialog *d = new MyDialog(); d->setAttribute(Qt::WA_DeleteOnClose); d->DoSomething(); d->show(); } else { d->DoSomething(); }
DoSomething() is a public function within MyDialog.
When d is NULL means that I have not opened the window, so I create, otherwise I assume that the window is already open, and then only the active DoSomething() function. But if I close d is not NULL but obviously goes wrong just meets the line d->DoSomething().I hope everything is clear.
-
@Gianluca86 Your dialog will be deleted when it is closed, but the pointer to it will not be changed. Why should it be changed and by whom? The dialog itself does not know whether there are any pointers pointing to it. So nobody assigns NULL to it.
-
@Gianluca86 One more comment: when dialog is deleted the pointer still contains the address but is NOT valid anymore (that's why your application would crash if you would try to use that pointer).
int *p = new int(); // p is a valid pointer delete p; // p still has the old value (the address) but is not valid any-more
-
I know, I would like to assign NULL when the window is closed, but I would not use the new signals.
For example, if the destroyer of Dialog emit a signal to the main window I can asegnare the NULL pointer. I just wanted to avoid this, but I believe there is no alternative. -
@Gianluca86 You could use http://doc.qt.io/qt-5/qobject.html#destroyed. You only need to add a slot for this signal and connect both.
-
@Gianluca86 said:
I know, I would like to assign NULL when the window is closed, but I would not use the new signals.
QPointer provides guarded pointers for
QObject
s. You can use it to hold a reference to your dialog and when the dialog is deleted the pointer will be set to NULL automatically. -
Both solutions are great, now I see what to use.
Thank you all -