为什么在 exec() 之前调用 quit() 不会退出应用程序? [英] Why does calling quit() before exec() not quit the application?

查看:25
本文介绍了为什么在 exec() 之前调用 quit() 不会退出应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个程序可以正常运行并显示主窗口?我希望它退出,因为 quit() 在构造函数中被调用.

Why does this program run normally and display the main window? I would expect it to exit since quit() is called in the constructor.

Main.cpp:

#include<QApplication>
#include"MainWindow.h"

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}

MainWindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
   qApp->quit();
}

void MainWindow::closeEvent(QCloseEvent *)
{
    qDebug("Hello world!");
}

推荐答案

调用 QCoreApplication::quit() 与调用 QCoreApplication::exit(0) 是一样的.

Calling QCoreApplication::quit() is the same as calling QCoreApplication::exit(0).

如果您查看后一个函数的docs:

If you look at the docs of the latter function:

这个函数被调用后,应用程序离开主事件循环并从对 exec() 的调用返回.exec() 函数返回返回代码.如果事件循环没有运行,这个函数什么都不做.

After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns returnCode. If the event loop is not running, this function does nothing.

在你的例子中,当 MainWindow 的构造函数被调用时,事件循环还没有开始,因此对 quit() 的调用什么都不做.

In you example, the event loop has not been started yet when MainWindows constructor is called, hence the call to quit() does nothing.

这篇关于为什么在 exec() 之前调用 quit() 不会退出应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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