9.3.  Dialogs

[ fromfile: dialogs.xml id: dialogs ]

QDialog is the base class for Qt dialogs. Dialog windows are mostly used for brief interactions with the user. A dialog window can be modal or nonmodal. Modal dialogs pop up when your program calls a static QMessageBox:: or QFileDialog:: convenience function. While the dialog box is on the screen, input is blocked to all other visible windows in the same application. Normal interactions with the application can resume when the user dismisses the modal dialog box. QDialog::exec() is another way to put a modal dialog on the screen. When the user completes the required response, the dialog can return data (e.g., a string or number) and/or a dialog code (QDialog::Accepted or QDialog::Rejected).

You can show() a QDialog like any QWidget. In this case, it is nonmodal, and the user can still interact with other windows of the application. Example 9.1 shows the difference between a modal dialog and and a nonmodal one that is popped up with show().

Example 9.1. src/widgets/dialogs/modal/main.cpp

[ . . . . ]
#include <QtGui>
int main (int argc, char* argv[]) {
    QApplication app(argc, argv);
    QProgressDialog nonModal;
    nonModal.setWindowTitle("Non Modal Parent Dialog");
    nonModal.show();                    1
    nonModal.connect(&nonModal, SIGNAL(finished()), 
            &app, SLOT(quit()));        2    
[ . . . . ]
    QFileDialog fileDialog(&nonModal, "Modal File Child Dialog");
    // 2 modal dialogs. exec() takes over all user interactions until closed. 
    fileDialog.exec();                  3
    QMessageBox::question(0, QObject::tr("Modal parentless Dialog"),
            QObject::tr("can you interact with the other dialogs now?"), 
            QMessageBox::Yes | QMessageBox::No);
    return app.exec();                  4
}
[ . . . . ]

1

Returns immediately

2

Termination condition

3

Similar to entering an event loop, returns when window closes.

4

Quits when nonModal closes

<include src="src/widgets/dialogs/modal/main.cpp" href="src/widgets/dialogs/modal/main.cpp" id="modaltest-cpp" mode="cpp"/>


Parents and Children

A QDialog with a parent widget always appears in front of its parent. Clicking the parent also raises the dialog. For nonmodal dialogs, this helps you avoid accidentally hiding them behind the main window. Modal dialogs always appear on top of other widgets created from that application regardless of parentage.

Input Dialogs

There are a number of predefined input dialogs you can reuse. $QTDIR/examples/dialogs/standarddialogs, shown in Figure 9.9, demonstrates many of them.

Figure 9.9.  Standard Dialogs

Standard Dialogs