Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the modality of QDialog at runtime?

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!

like image 214
user1416940 Avatar asked Feb 20 '23 08:02

user1416940


1 Answers

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();
}
like image 159
Ammar Avatar answered Mar 02 '23 17:03

Ammar