0
votes

I have an application with two top level windows (i.e. having no parent widget), which are rather independent of each other and I want to enable the users switch between them any time they want. However when one of these windows opens a modal dialog by calling dlg.exec(), it blocks also the other window. The user cannot switch to it at all. I managed to create modal dialogs with dlg.setWindowModality(Qt::WindowModal) and then dlg.show() but his shows the dialog and continues without waiting for the return value from the dialog. So if I want to process the result of the modal dialog (typically querying for some information - e.g. open/save file dialog), I need to move the functionality processing the dialog result some other function (other than the one which opened the dialog) and either use ad hoc signal/slot connection, some callback or let the dialog itself know how to process the result, which in my view is a bad design. And it is especially difficult with built in dialogs like file dialogs or QMessageBox...

So my question is: is there any trick in Qt which would let me have two top level windows, which the user can freely switch between, and at the same time be able to open modal dialogs like with dlg.exec(), which would block only one window and wait for the dialog result but do not block the other window? I think it is not possible but maybe I missed something. I mean for example some magic with threads and QEventLoop which is unknown to me? As far as I know the widgets must reside in the main thread, which is a bit trouble in this case if I wanted to use threads...

PS: to let you have better idea of what I need, imagine Excel in one window and its VB editor in the other one. The user is able to switch to VB at any time.

1

1 Answers

0
votes

It works using QDialog::exec().

Here is a working example:

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    MainWindow w2;
    w2.show();

    return a.exec();
}

mainwindow.cpp

// I skipped the rest of the code as it is just the template code from Qt Creator template project.
void MainWindow::on_pushButton_clicked() // mainwindow.ui creates a QPushButton named "pushButton"
{
    QMessageBox mb(this);
    mb.setModal(true);
    mb.setWindowModality(Qt::WindowModal);
    mb.exec();
}

It opens 2 windows and I can interact with both independently regardless if the other has its QMessageBox opened or not.