Important: Please read the Qt Code of Conduct -

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");
        bool ok =;
            // only show login dialog if the connection is valid and established
            LoginDialog login;
            // showing this window will depend on a successful login, login check not implemented yet
            MainWindow w;
            // shows error message if the connection couldn't get established
            QMessageBox* msg = new QMessageBox(nullptr);
        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.

  • You're declaring your window inside the if-true body, and its scope is limited to this body... You should declare a pointer on a MainWindow and allocate it using new.

    Edit: this works similar with your LoginDialog instance.

  • Lifetime Qt Champion

    First: you should call

    instead of;

    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.

Log in to reply