I use this code:
MyDialog *md = new MyDialog();
md -> show();
to open a dialog window in Qt. Will md
be deleted automatically when the dialog window is closed or do I need to run delete md
when the window is finished?
In your little piece of code you need to delete it, because it doesn't have a parent, if you set a parent, the parent will delete it's children and you only need to delete the "main-window" (the window that doesn't have a parent).
Also for QWidget derived classes you can use the: Qt::WA_DeleteOnClose
flag and then the memory will be deallocated when the widget closes, see the documentation here
Then code will become:
MyDialog *md = new MyDialog();
md->setAttribute(Qt::WA_DeleteOnClose);
md->show();
Yes. Unless you pass this
while this
is a QWidget
or any other QWidget
:
MyDialog *md = new MyDialog(this);
md->show();
you need to:
delete md;
at some point in order to release its memory. Also you need to make sure in this case that the object tree is well linked. What you can also do is call setAttribute(Qt::WA_DeleteOnClose);
on md
so that when you close the dialog, its memory will also be released as Zlatomir
said. However if you need md
to live after it was closed setAttribute(Qt::WA_DeleteOnClose);
is not an option. This is also dangerous and could lead to access violation/segmentation fault if you are not careful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With