Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to delete dialog window pointer in Qt?

Tags:

c++

qt

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?

like image 574
Minimus Heximus Avatar asked Dec 05 '22 23:12

Minimus Heximus


2 Answers

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();
like image 98
Zlatomir Avatar answered Jan 05 '23 17:01

Zlatomir


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.

like image 45
Iuliu Avatar answered Jan 05 '23 15:01

Iuliu