Nicholas Yu
Nicholas Yu

Reputation: 343

QT: how to exit application and close UI

I tried to use qApp->exit() to exit application and close UI. but I failed the UI is still there after qApp->exit() executed. Anyone can help to figure out why? thanks a lot.

#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.
}

Upvotes: 1

Views: 7128

Answers (3)

Vladimir Bershov
Vladimir Bershov

Reputation: 2832

Working code:

#include <QMetaObject>
//...
QMetaObject::invokeMethod(qApp, "quit",
    Qt::QueuedConnection);

Or for widgets:

QMetaObject::invokeMethod(this, "close",
    Qt::QueuedConnection);

Upvotes: 0

Jeka
Jeka

Reputation: 1374

It will not help you in constructor, because of no event loop started yet.

In such case you can use QTimer::singleShot() with timeout equal zero. It will cause calling what you need when event loop started. Also it is good idea to use initialization method and check it in main:

Window w;
if ( !w.init() )
   return 1;
w.show();
return a.exec();

Upvotes: 2

VP.
VP.

Reputation: 16685

@thuga is right. The problem you have is caused by your wrong code: you call qApp->exit() before right in your constructor, where your application has not started it's message cycle yet (by 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();
}

Upvotes: 4

Related Questions