How can I change the modality of QDialog at runtime?

user1416940 picture user1416940 · May 25, 2012 · Viewed 10k times · Source

I have a QDialog and I read a lot about the differences of show(), exec() and open(). Unfortunately I never found a solved solution to change the modality of a dialog at runtime. I have an application and from there my QDialog is started. I have a toggle button in this dialog and with clicking on it the QDialog should change the modality,so that it is possible to interact with the application - but this shouldn't happen all the time - just when the toggle button is checked.

Is there a possibility? I could not solve the problem with setting setModal(true/false) this just allows me to start it modal, toggle the button and set it to non modal, but then I can't go back to modal.

Here some code:

Starting the dialog:

from the main window:

_dialog = new ToggleModalDialog(this, id, this);
_dialog->setWindowModality(Qt::ApplicationModal);
_dialog->open();

and here in the toggled slot in the ToggleModalDialog

void ToggleModalDialog::changeModality(bool checkState)
{
    if(checkState)
    {
        this->setWindowModality(Qt::NonModal);
        ui->changeModalityButton->setChecked(true);
        this->setModal(false);
    }
    else
    {
        this->setWindowModality(Qt::ApplicationModal);
        ui->changeModalityButton->setChecked(true);
    }

Thanks in advance!

Answer

Ammar picture Ammar · May 25, 2012

You can use eitherQDialog::setModal(bool) or setWindowModality(Qt::ApplicationModal). But the documentation of setWindowModality() says something extra which is..

Changing this property while the window is visible has no effect;
you must hide() the widget first, then show() it again.

So your code should look like following..

void ToggleModalDialog::changeModality(bool checkState)
{
    if(checkState)
    {
        this->setWindowModality(Qt::NonModal);
        ui->changeModalityButton->setChecked(true);
    }
    else
    {
        this->setWindowModality(Qt::ApplicationModal);
        ui->changeModalityButton->setChecked(true);
    }

    this->hide();
    this->show();
}