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.
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. =)
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.
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();
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With