Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt application does not quit

can anyone tell me why this simple qt application does not quit

int main(int argc, char* argv[])
{ 
QApplication app(argc,argv);
 QWidget* w = new QWidget(nullptr);
 w->show();
 w->close();
 app.exec();
 return 0;
}

I've tried to show all top level widgets with this loop

for (auto t : QApplication::topLevelWidgets())
    {
        t->show();
    }

and the widget not destroyed after close,

even adding

w->setAttribute(Qt::WA_QuitOnClose);

does not help.

I'm using visual studio 2013 and qt with version 5.4

like image 636
zapredelom Avatar asked May 24 '26 04:05

zapredelom


1 Answers

The answere is simple:

QApplication will quit as soon as you close the last window - however, this only applies if the window is closed while the application runs!

In your example, at the time your run the application using a.exec(), there are no open windows. Thus, no window gets ever closed while the application runs and it won't quit. It will work as soon as you call w->close(); after you started the application.

If you still need to close the widget before starting (for whatever reason), you can do the following:

w->show();
QMetaObject::invokeMethod(w, "close", Qt::QueuedConnection);
app.exec();

This way, close will be called as soon as the application enters it's eventloop.

like image 148
Felix Avatar answered May 26 '26 17:05

Felix