humroben humroben - 1 year ago 68
C++ Question

Qt Parent to delete variable after child has closed

I'm writing an application in C++ using the Qt library. There is a central window (the parent) and all the children are launched when needed. Since a number of these windows can be open multiple times, but display different data, I'm declaring the objects with

. Here is an example of what I've got:


View_Window *SomeWindow;


void Home_Window::on_WindowButton_clicked()
SomeWindow = new View_Window();

What I want to do, is delete the object, when the window is closed to reduce the memory footprint of the application. I've already been able to delete all of the objects contained in the child window to reduce memory usage, but the core object still lingers, and if, through a single day a user opens and closes 1000's of windows, and each object holds onto 40-50KB of memory, the footprint of the application goes from a couple of MBs of memory to 100's of MBs of Memory.

I've not been able to find a guide online that would allow me to achieve this. I was considering a slot and signal pair, as I know that when a window is closed, it sends the
signal. Only issue, is I've not tried to setup a signal and slot pair like this.

Any suggestions are appreciated.

Answer Source

to delete the window when it is closed, you can set the WA_DeleteOnClose attribute on it. Your on_WindowButton_clicked() should look something like:

void Home_Window::on_WindowButton_clicked()
    View_Window* w= new View_Window();

This way, you don't have to worry about destroying w yourself, it will get deleted automatically when it is closed.