Reputation: 197
I have multiple windows so want to make sure to prevent memory leaks.
What's the correct way of initialising WA_DeleteOnClose
. For ex. if I'm opening a new window should I do setAttribute(Qt::WA_DeleteOnClose,true)
on both the current window (this
) and the new window, as shown below?
void Settings::on_commandLinkButton_clicked()
{
this->setAttribute(Qt::WA_DeleteOnClose,true); //---> current window
this->close();
newwindow = new Patients(this);
newwindow ->setAttribute(Qt::WA_DeleteOnClose,true); //---> new window
newwindow -> show();
}
Upvotes: 2
Views: 1009
Reputation: 1735
I just made a test with the possible combinations.
If WA_DeleteOnClose
is set, the destructor is called immediately.
If WA_DeleteOnClose
is not set, and the dialog is the child of the parent to be deleted, it will be deleted before its parent.
Both can be done and the dialog is still only deleted once.
My test code is as followed:
dialog.cpp:
#include "dialog.h"
#include <QDebug>
Dialog::Dialog(const QString &name, QWidget *parent) : QDialog{parent}
{
m_name = name;
this->setWindowTitle(m_name);
qDebug() << "Constructing dialog" << m_name;
}
Dialog::~Dialog()
{
qDebug() << "Destructing dialog" << m_name;
}
mainwindow.cpp:
#include "mainwindow.h"
#include "dialog.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
m_dialog_1 = new Dialog{"Alpha"};
m_dialog_1->setAttribute(Qt::WA_DeleteOnClose, true);
m_dialog_1->show();
m_dialog_2 = new Dialog{"Beta", this};
m_dialog_2->setAttribute(Qt::WA_DeleteOnClose, true);
m_dialog_2->show();
m_dialog_3 = new Dialog{"Charlie", this};
m_dialog_3->setAttribute(Qt::WA_DeleteOnClose, false);
m_dialog_3->show();
}
MainWindow::~MainWindow()
{
}
Upvotes: 2