PDA

View Full Version : How to close all windows that were created in main()?



Mister_Crac
10th November 2006, 13:48
If you create more than one window inside of main(), how do destroy all of them when the main window is closed by the user? So he does not have to close all windows manually?

Code example:


#ifndef CLOSETEST_H
#define CLOSETEST_H
#include <QtGui>

class CloseTest : public QWidget {

public:
CloseTest(QWidget *parent = 0);
};

#endif



#include "CloseTest.h"

CloseTest::CloseTest(QWidget *parent)
{
QHBoxLayout *layout = new QHBoxLayout;
QLabel *label = new QLabel("This is a test");

layout->addWidget(label);
setLayout(layout);
}



#include <QApplication>
#include "CloseTest.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QLabel main("This is the main label");
main.resize(300,150);
main.show();

CloseTest ct;
ct.show();

return app.exec();
}

Mister_Crac
10th November 2006, 14:06
I tried this:



QObject::connect(&main, SIGNAL(destroyed()), &ct, SLOT(close()));


but to no avail.

jpn
10th November 2006, 14:11
You have to set the Qt::WA_DeleteOnClose attribute to true so that the widget gets deleted upon close:


#include <QtGui>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QLabel* label1 = new QLabel("a");
label1->setAttribute(Qt::WA_DeleteOnClose, true);
a.connect(label1, SIGNAL(destroyed()), &a, SLOT(quit()));
label1->show();

QLabel* label2 = new QLabel("b");
label2->setAttribute(Qt::WA_DeleteOnClose, true);
a.connect(label2, SIGNAL(destroyed()), &a, SLOT(quit()));
label2->show();

return a.exec();
}


EDIT: Btw, make sure you allocate widgets on stack if you set Qt::WA_DeleteOnClose attribute! Otherwise you'll get a crash due to double delete...

Mister_Crac
10th November 2006, 14:50
EDIT: Btw, make sure you allocate widgets on stack if you set Qt::WA_DeleteOnClose attribute! Otherwise you'll get a crash due to double delete...

On the stack? I thought this allocates an object on the heap:


Object *example = new Object;


Anyways it works like you suggested, thank you! :)

jpn
10th November 2006, 16:32
On the stack? I thought this allocates an object on the heap:
Argh, sorry. I was in a hurry when answering. I meant heap while I still wrote stack.. ;)

Matt Smith
12th November 2006, 00:50
If you create more than one window inside of main(), how do destroy all of them when the main window is closed by the user? So he does not have to close all windows manually?

Try the static/slot function QApplication::closeAllWindows(). Documentation to be found here (http://doc.trolltech.com/4.1/qapplication.html#closeAllWindows).

Mister_Crac
13th November 2006, 10:57
Try the static/slot function QApplication::closeAllWindows(). Documentation to be found here (http://doc.trolltech.com/4.1/qapplication.html#closeAllWindows).

Hooray for another possibility! ;)