![](/img/trans.png)
[英]QT QTcpServer in thread; how to close listening server on exit?
[英]QT: how to exit application and close UI
我試圖使用qApp-> exit()退出應用程序並關閉UI。 但是我失敗了,執行qApp-> exit()之后,UI仍然存在。 任何人都可以幫助找出原因嗎? 非常感謝。
#include "clsDownloadUpdateList.h"
#include <QApplication>
#include <qtranslator.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator translator;
translator.load("en-CN_upgrader");
qApp->installTranslator(&translator);
clsDownloadUpdateList w;
w.show();
return a.exec();
}
clsDownloadUpdateList::clsDownloadUpdateList(QWidget *parent) :
QMainWindow(parent),
_state(STOP),
ui(new Ui::clsDownloadUpdateList)
{
ui->setupUi(this);
this->setWindowTitle("GCS Upgrader");
// other code
// here comes the code to exit application
qApp->exit();
// but the UI is still there.
}
@thuga是正確的。 您遇到的問題是由您的錯誤代碼引起的:您在構造函數中調用qApp->exit()
之前,而在該構造函數中,應用程序尚未啟動(消息傳遞周期是通過a.exec()
)。
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator translator;
translator.load("en-CN_upgrader");
qApp->installTranslator(&translator);
clsDownloadUpdateList w; // <- you call qApp->exit() right here, before a.exec();
w.show();
return a.exec();
}
由於尚未啟動任何事件循環,因此對構造函數無濟於事。
在這種情況下,可以使用超時等於零的QTimer :: singleShot()。 事件循環開始時,它將導致調用您需要的內容。 另外,最好使用初始化方法並在main中對其進行檢查:
Window w;
if ( !w.init() )
return 1;
w.show();
return a.exec();
工作代碼:
#include <QMetaObject>
//...
QMetaObject::invokeMethod(qApp, "quit",
Qt::QueuedConnection);
或對於小部件:
QMetaObject::invokeMethod(this, "close",
Qt::QueuedConnection);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.