QPointer and deleting objects

6.2k views Asked by At

I've got a Qt App that uses QPointers to bring up new UI Dialogs (Widgets). The main app can have numerous of the same widget loaded with different data. The problem I'm having is in deleting and freeing the memory for each widget. If I monitor the RAM usage of the program, each time I click the button to open one of these new widgets, it increases the ram and when I close the widget, it doesn't seem to be freeing the ram. I've tried using deleteLater and other solutions but keep getting crashes in the program.

Some example code is here:

QPointer<ListReservations> listResWindow = new ListReservations(resID);
listResWindow->setNum(numpeople);
listResWindow->show();

This will call the "ListReservations" widget which is declared as a QDialog (NOT modal). In that dialog I then have a button to close the window that calls the QWidget::close() slot.

I guess the question is how does my main program (that has the QPointer) know when the dialog is closed and then free the dialog and (if possible) delete the pointer to save even more memory...

I thought you might be able to do a QConnect() to the QPointer object, but I can't seem to find any signals or slots that would allow the passing of the pointer, much less send the signal once the dialog is indeed closed and ready for deletion.

Maybe I need some sort of function in the main program that takes a generic pointer object and then have the QDialog call that before calling it's own close slot? In that function it would pass itself to be destroyed? Just throwing out ideas that I've tried to implement but failed at....

I don't think I can reuse the same pointer elsewhere because in theory you could have multiple ListReservations windows open at the same time.

1

There are 1 answers

3
Ton van den Heuvel On BEST ANSWER

Make sure that you set the Qt::WA_DeleteOnClose attribute flag on your dialog using QWidget::setAttribute(). That should make sure that the dialog is properly destroyed when it is closed. See the Qt documentation for more details.

Assuming that memory is now properly freed, the pointer should invalidate itself, from the Qt documentation:

A guarded pointer, QPointer, behaves like a normal C++ pointer T *, except that it is automatically set to 0 when the referenced object is destroyed (unlike normal C++ pointers, which become "dangling pointers" in such cases)