3

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

Dragster
  • 97
  • 1
  • 7
zapredelom
  • 1,009
  • 1
  • 11
  • 28
  • 1
    Does this help: [Correct way to quit a Qt program](http://stackoverflow.com/questions/8026101/correct-way-to-quit-a-qt-program) – Samer Tufail Mar 01 '16 at 15:47
  • i don't what to force quit application , I what to application end its execution after widget is closed – zapredelom Mar 01 '16 at 15:50
  • 1
    When you call `show()` and then immediately `close()` you never see a widget. Do not call `close()`, it will be closed by the user by pressing "x" on window decoration. btw. you should return the number/error code which returns `app.exec()`. – Radek Mar 01 '16 at 17:08
  • @Radek Your comments are perfectly true, but has noting to do with my question. This code is just a sample which is reproducing my issue. – zapredelom Mar 01 '16 at 18:36
  • @zapredelom The `app.exec()` starts the infinite event loop, it only stops when the last top widget is closed by event e.g. by user interaction, or manualy in the code send the event as in the answer bellow. All GUI frameworks work like this. – Radek Mar 02 '16 at 09:43

1 Answers1

5

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.

Felix
  • 6,885
  • 1
  • 29
  • 54