Skydyver
Skydyver

Reputation: 15

How to create and display the MainWindow outside the Main()?

I've made LONG research on the web but can't find anything clear. I think the answer is obvious but i'm beginer in Qt. Why this code doesn't work ? My windows just popup realy fast.

Main.cpp

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

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

return a.exec();
}

Test.cpp

#include "test.h"

Test::Test()
{
 MainWindow w;
 w.show();
}   

And this one work (the window keep open) :

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

Thank you !

Upvotes: 0

Views: 171

Answers (1)

user2100815
user2100815

Reputation:

The window closes because it is local variable of the Test constructor, and when the constructor exits, its destructor gets called, which closes it. You need to make the window object a member variable of the Test class.

Upvotes: 2

Related Questions