2012-04-09 71 views
6

爲什麼這個程序運行正常並顯示主窗口?我期望它會在構造函數中調用quit()而退出。爲什麼在exec()不退出應用程序之前調用quit()?

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!"); 
} 

回答

7

調用QCoreApplication::quit()是與調用QCoreApplication::exit(0)

如果你看一下後者的功能的docs

這個函數被調用後,應用程序離開主 事件循環,並返回從調用exec()。 exec()函數 返回returnCode。 如果事件循環未運行,則此功能 不執行任何操作

在您例如,事件循環尚未啓動時MainWindow的構造函數被調用,因此調用quit()什麼都不做。

+0

好感謝您的幫助。 – user1318674 2012-04-09 23:04:02

6

由於QCoreApplication::quit()在事件循環啓動之前是空操作,所以您需要延遲通話直到啓動。因此,將延遲方法調用排隊到quit()

以下行是functionally identical,要麼一會工夫:

QTimer::singleShot(0, qApp, &QCoreApplication::quit); 
//or 
QTimer::singleShot(0, qApp, SLOT(quit())); 
// or - see https://stackoverflow.com/a/21653558/1329652 
postToThread([]{ QCoreApplication::quit(); }); 
// or 
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection); 
相關問題