C++ 如何正确关闭 Qt 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17061572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:53:37  来源:igfitidea点击:

How to close correctly a Qt program?

c++qt

提问by JBL

When I try to close my Qt program, it just keeps running in the background though there's no window anymore.

当我尝试关闭我的 Qt 程序时,它只是在后台继续运行,尽管不再有窗口。

Basically, I would like to know what I should do so it closes properly when I click the red cross on my main window (which has no parent).

基本上,我想知道我应该怎么做,以便当我单击主窗口(没有父窗口)上的红十字时它会正确关闭。

Following this link, I tried a few things like :

按照此链接,我尝试了一些操作,例如:

QApplication app(argc, argv);
//...
app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
return app.exec();

or

或者

QApplication app(argc, argv);
//...
app.setQuitOnLastWindowClosed(true);
return app.exec();

but neither work, the process still stays in memory, after the cross is clicked.

但两者都不起作用,点击十字架后,该过程仍保留在内存中。

Then, how can I close correctly my program ?

那么,如何正确关闭我的程序?

回答by Pavel Strakhov

You can close your application manually using QApplication::quit().

您可以使用 手动关闭您的应用程序QApplication::quit()

By default the execution is terminated when the last top level window with the Qt::WA_QuitOnCloseattribute has been closed. You don't need to connect lastWindowClosedto quitbecause it repeats the default setQuitOnLastWindowClosedbehavior. You don't need to do setQuitOnLastWindowClosed(true)either because it's true by default. The code you've posted does nothing (if nothing is changed somewhere else).

默认情况下,当具有该Qt::WA_QuitOnClose属性的最后一个顶级窗口已关闭时,执行将终止。您不需要连接lastWindowClosed到,quit因为它重复了默认setQuitOnLastWindowClosed行为。您不需要这样做setQuitOnLastWindowClosed(true),因为默认情况下它是真的。您发布的代码什么也不做(如果其他地方没有任何更改)。

Possible solutions:

可能的解决方案:

  • Check your main window attributes. Maybe you have removed Qt::WA_QuitOnCloseattribute.
  • If you have reimplemented closeEventin your top level window, check that close event is being accepted.
  • Check if there are some other top level widgets that may be hidden but not closed. Use QApplication::topLevelWidgets()to list them.
  • 检查您的主窗口属性。也许你已经删除了Qt::WA_QuitOnClose属性。
  • 如果您已closeEvent在顶级窗口中重新实现,请检查关闭事件是否被接受。
  • 检查是否有其他一些可能隐藏但未关闭的顶级小部件。使用QApplication::topLevelWidgets()一一列举。