Important: Please read the Qt Code of Conduct -

Open a QMainWindow from QMainWindow and wait until it closes

  • Hello,

    I am getting a segmentation fault with this code, at the last line:

       SettingsWindow *settingsWin =  new SettingsWindow(this);
        QEventLoop loop;
        connect(settingsWin, SIGNAL(destroyed()), &loop, SLOT(quit()));
        orbiterPath = settingsWin->orbiterPath;

    I want to open the settings window and wait until it closes (Something like .exec() in QDialog). I noticed when debugging all settingsWin variables are not accessible. What is the correct way to open a QMainWindow and wait until it closes?

  • @Abdullah-Radwan

    Hi and welcome to devnet forum

    Not sure if I understand completely what you trying to do. However, when I see the sequence you are giving above and assume that this is a complete block copied from your source, it is the event loop.

       SettingsWindow *settingsWin =  new SettingsWindow(this);    // creates the setting what might be ok
        settingsWin->show();                                                                           // shows the window and is ok
        QEventLoop loop;                                                                                  // creates event loop
        connect(settingsWin, SIGNAL(destroyed()), &loop, SLOT(quit()));                  // connects destroyed signal of settings window to quit loop
        loop.exec();                             // starts the loop and until exit respectively quit
        orbiterPath = settingsWin->orbiterPath;                       // settingsWindow must be gone at this point

    See comments above. The event loop has simply to wait until it is exited. The reason for exit is quit call, but quit is only called when the object is destroyed. When the object is destroyed you cannot access anymore and receive the seg fault.

  • @koahnig Thanks for the detailed explanation. I thought .destroy() removes the graphical elements, not the class itself. I removed delete on close attribute and made a custom signal for close event by overriding closeEvent() method. This how it looks in the code:

    Show function in the code:

    SettingsWindow *settingsWin = new SettingsWindow(this);
    QEventLoop loop;
    connect(settingsWin, SIGNAL(closed()), &loop, SLOT(quit()));


    class SettingsWindow : public QMainWindow
        void closed();
        void closeEvent(QCloseEvent *bar);


    void SettingsWindow::closeEvent(QCloseEvent *bar){
        emit closed();

Log in to reply