Qt windows crashing when inside if-body
-
Hey,
I'm a beginner to Qt5.6 and I have some trouble. I'm working on this code:
#include "mainwindow.h" #include "logindialog.h" #include <QApplication> #include <QtSql> #include <QMessageBox> int main(int argc, char *argv[]) { QApplication a(argc, argv); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setUserName("user"); db.setPassword("pass"); db.setDatabaseName("db"); bool ok = db.open(); if(ok) { // only show login dialog if the connection is valid and established LoginDialog login; login.show(); // showing this window will depend on a successful login, login check not implemented yet MainWindow w; w.show(); } else { // shows error message if the connection couldn't get established QMessageBox* msg = new QMessageBox(nullptr); msg->setIcon(QMessageBox::Critical); msg->setWindowTitle("Error"); msg->setText("Error:\n\n"+db.lastError().text()); msg->show(); } return a.exec(); }
As you can see, I want to check if the connection is valid before showing the LoginDialog-formular (or even the MainWindow). Before I added this if-Statement, both windows worked just fine. But after I added the check the program crashes immediately, without any error messages (just the crash note in Creator). If the connection parameters are wrong, it shows the QMessageBox, just as intended. But as soon as the program enters the if-true-body, the program shuts down.
What did I miss? I'm thankful for any help.
-
First: you should call
login.exec(); instead of login.show();
else the MainWindow will always be visible, even before login is finished.
Second: you should declare login and w before if block. You can still declare login inside if block if you use exec() (because exec() blocks until the dialog is closed).
Your app crashes because login and w are destroyed after if block is executed. Actually it does not crash - your dialog and main window are destroyed after if block and thus not shown.