退出 Qt 程序的正确方法?
我应该如何退出 Qt 程序,例如加载数据文件时,发现文件损坏,并且用户需要退出该应用程序或重新启动数据文件?
我应该:
- 调用
exit(EXIT_FAILURE)
- 调用
QApplication::quit()
- 调用
QCoreApplication::quit()
以及(2)和之间的区别(3)?
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file?
Should I:
- call
exit(EXIT_FAILURE)
- call
QApplication::quit()
- call
QCoreApplication::quit()
And difference between (2) and (3)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
QApplication 派生自 QCoreApplication,因此继承了
quit()
,它是QCoreApplication
的公共槽,因此与QApplication::quit()
没有区别。代码>和QCoreApplication::quit()
。正如我们可以在
QCoreApplication::quit()
它“告诉应用程序退出并返回代码 0(成功)。”。如果您因为发现文件损坏而想要退出,那么您可能不希望以返回代码零退出(这意味着成功),因此您应该调用
QCoreApplication::exit()
因为您可以提供一个非零 returnCode,按照惯例,它指示错误。重要的是要注意“如果事件循环未运行,则此函数 (QCoreApplication::exit()) 不执行任何操作”,因此在这种情况下,您应该调用 exit(EXIT_FAILURE) 。
QApplication is derived from QCoreApplication and thereby inherits
quit()
which is a public slot ofQCoreApplication
, so there is no difference betweenQApplication::quit()
andQCoreApplication::quit()
.As we can read in the documentation of
QCoreApplication::quit()
it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should callQCoreApplication::exit()
because you can provide a non-zero returnCode which, by convention, indicates an error.It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call
exit(EXIT_FAILURE)
.您可以调用
qApp->exit();
。我一直用它并且从来没有遇到过问题。如果您的应用程序是命令行应用程序,您可能确实希望返回退出代码。代码是什么完全取决于您。
You can call
qApp->exit();
. I always use that and never had a problem with it.If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
在搜索这个问题时,我在 文档 中发现了这个示例。
当然,比照您的特定操作。
连同这张纸条。
While searching this very question I discovered this example in the documentation.
Mutatis mutandis for your particular action of course.
Along with this note.
如果您使用 Qt Jambi,这应该可以工作:
If you're using Qt Jambi, this should work:
如果您需要从 main() 关闭您的应用程序,您可以使用此代码
如果未安装 OpenSSL,程序将终止
if you need to close your application from main() you can use this code
The program will terminated if OpenSSL is not installed
示例
example