Search code examples
qtwindowshow

pause function while child window is displayed in Qt


in Qt Creator I have a mainwindow and a QWidget as tool-window (setWindowFlags(Qt::tool)). When I call the tool window the user can change some settings. These changes then alter some data in the mainwindow.

I create the widget, show it, then I want to update the data in mainwindow, but the function doesn't wait for the widget to close. So the update procedures after the show are imidiately executed and have no effect. When I show a QMessageBox the function waits for the user to close it.

Is there a flag or something I can set for the QWidget so the function waits?

void userclicksonsettings(){
 settings = new Settings(this);  // Settings is a QWidget-class with ui
 settings->show();
 // function should wait till settings is closed
 // set up mainwindow with new values
}

Thanks.


Solution

  • I just solved it. Using QDialog instead of QWidget as base class allows to call the window with QDialog::exec(); and the parent widget will pause until the window is closed again.

    Edit: here is the source of the solution I just digged out of a backup disk. I have to say though, it's some years ago I last used Qt and this code, so it could be incorrect. I hope it helps to get the idea.

    settingsForm.h

    #include <QDialog>
    class SettingsForm : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit SettingsForm(QWidget *parent = 0);
        ~SettingsForm();
    // other variables and slots etc.
    };
    

    settingsForm.cpp

    #include "settingsform.h"
    #include "ui_settingsForm.h"
    
    #include <QColorDialog>
    
    SettingsForm::SettingsForm(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::SettingsForm)
    {
        ui->setupUi(this);
        this->setWindowFlags(Qt::Tool);
    
    // initializing functions
    }
    
    SettingsForm::~SettingsForm()
    {
        delete ui;
    }
    

    mainwindow.h

    #include "settingsForm.h"
    // ...
    

    To call the settingsWindow in from the mainwindow initialize the object and call it like a QDialog

    mainwindow.cpp

    settingsform = new SettingsForm(this);
    if(settingsform->exec() == QDialog::Accepted){
        // update form from settings
    }
    

    I had also a settings-class for all the variables that could be set with the form, which was passed to the settingsForm and updated when the user clicked OK.