PDA

View Full Version : destructor not working



habbas33
28th September 2016, 12:41
Hi.. I have make a simple project and try to understand destructor. but I
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
#include "QDebug.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

qDebug()<<"start MainWindow";

}

MainWindow::~MainWindow()
{
delete ui;
qDebug()<<"end MainWindow";
}

void MainWindow::on_pushButton_clicked()
{
Dialog *dia = new Dialog;
dia->show();
}



#include "dialog.h"
#include "ui_dialog.h"
#include "QDebug.h"

Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
qDebug()<<"start Dialog";
}

Dialog::~Dialog()
{
delete ui;
qDebug()<<"end Dialog";
}


The problem is that when I close qDialog... it doesnot goes to the ~dialog and print "end dialog"....
however, when I close mainWindow... goes to the ~mainWindow and print end mainWindow....

Please tell me how to go to the destructor for dialog and the reason behind it....

Best Regards,

Haider

Lesiok
28th September 2016, 14:03
You must call destructor somewhere in code. First option is remeber pointers to Dialog objects in MainWindow and delete them in MainWindow destructor. Second is set MainWindow as parent of Dialog (change line 24 to this) :
Dialog *dia = new Dialog(this);
Third option is add this line in Dialog constructor :
setAttribute(Qt::WA_DeleteOnClose);

anda_skoa
28th September 2016, 14:20
The problem is that when I close qDialog... it doesnot goes to the ~dialog and print "end dialog"....
however, when I close mainWindow... goes to the ~mainWindow and print end mainWindow....

As Lesiok already explained you are not deleting the dialog.
You are apparently deleting the main window, probably because it is allocated on the stack in main() and deleted when the scope of that function ends.

Cheers,
_

Ginsengelf
28th September 2016, 15:00
Hi, you can either pass the mainwindow as a parent to the constructor of Dialog when you create the object (then MainWindow's destructor will take care of destruction), or you have to delete the dialog yourself.

Ginsengelf

habbas33
29th September 2016, 06:51
Thanks it works :)