Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a qt programming if initialization failed?

Tags:

c++

qt

MainWindows::MainWindow(QWidget *parent) :
                 QMainWindow(parent) , ui(new Ui::MainWindow) {
      ui->setupUi(this);

      some initialization code here
}

I want to terminate the whole application if the initialization failed, how could I do this?

Thanks.

like image 376
Jichao Avatar asked Nov 29 '22 15:11

Jichao


1 Answers

qApp->exit() and this->close() both won't work when called within MainWindow's constructor.

The normal Qt int main() function looks like this:

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    MainWindow mainWindow;
    mainWindow.show();

    return application.exec();
}

...and qApp->exit() only works from within the qApp->exec()/application.exec() main loop, which, as you can see in int main(), you aren't yet within. It therefore has no effect.

And with this->close(), MainWindow() hasn't finished been created yet, and hasn't been shown yet, so it's not open - if it's not open, it can't be closed. =)

Using delayed initialization

I think the easiest way to solve this is to delay your initialization until after the constructor finishes:

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    MainWindow mainWindow;
    if(mainWindow.Initialize() == false)
        return 0;

    mainWindow.show();
    return application.exec();
}

Normally I prefer/recommend initializing in the constructor of classes, but here an exception needs to be made to work around this unusual circumstance.

Using a 'failed state' flag

Other ways of doing the same thing would be to continue to initialize in the constructor, but use a flag to mark that the MainWindow has "failed to initialize":

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    MainWindow mainWindow; //Initialize in constructor, like normal.
    if(mainWindow.Failed()) //Check results.
    {
        return 0;
    }

    mainWindow.show();
    return application.exec();
}

Using exceptions

Exceptions are also another way to handle this situation - but make sure you catch it, so no error messages get displayed by the OS (I forget if Windows detects). In your initialization, you report the error yourself, so you can report it with details.

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    try
    {
        MainWindow mainWindow; //Initialize in constructor, like normal.

        mainWindow.show();
        return application.exec();
    }
    catch(...)
    {
        return 0;
    }
}
like image 67
Jamin Grey Avatar answered Dec 05 '22 18:12

Jamin Grey