QT应用程序不会退出 [英] qt application does not quit

查看:602
本文介绍了QT应用程序不会退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这个简单的qt应用程序不退出

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;
}

我试图用此循环显示所有顶级小部件

Iv'e tryed to show all top level widgets with this loop

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

并且关闭后窗口小部件未销毁,

and the widget not destroyed after close,

甚至添加

w->setAttribute(Qt::WA_QuitOnClose);

没有帮助.

我正在使用Visual Studio 2013和5.4版本的qt

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

推荐答案

答案很简单:

QApplication将在您关闭最后一个窗口后立即退出-但是,仅在应用程序运行时关闭该窗口的情况下才适用!

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

在您的示例中,使用a.exec()运行应用程序时,没有打开的窗口.因此,在应用程序运行时不会关闭任何窗口,并且不会退出.启动应用程序后,只要您调用w->close(); ,它就会起作用.

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();

这样,一旦应用程序进入事件循环,就会立即调用close.

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

这篇关于QT应用程序不会退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆