Сделать окно модальным qt

Обновлено: 28.04.2024

Программа, показанная на рисунке, является результатом создания собственного диалогового окна. При запуске на экране окно с кнопкой Press Me (Нажми меня), нажатие на которую отображает диалоговое окно ввода имени First Name (Имя) и фамилии Last Name (Фамилия).

В файле main.cpp создается виджет класса StartDialog, предназначенный для запуска диалогового окна.

Класс StartDialog унаследован от класса кнопки нажатия. Сигнал clicked() соединяется в методе connect() со слотом slotButtonClicked(). В этом слоте создается объект диалогового окна InputDialog, который не имеет предка.

Примечание: Диалоговые окна, не имеющее предка, будут центрироваться по экрану. Окна с предками будут отцентрированы относительно предка.

В операторе if производится запуск диалогового окна. После его закрытия управление передается основной программе и метод exec() возвращает значение нажатой пользователем кнопки. В том случае, если пользователем была нажата кнопка Ok, произойдет отображение информационного окна с введенными в диалоговом окне данными. По завершении метода диалоговое окно нужно удалить самому, так как у него нет предка, который позаботится об этом.

Для создания своего собственного диалогового окна нужно унаследовать класс QDialog. Класс InputDialog содержит два атрибута — указатели m_ptxtFirstName и m_ptxtLastName на виджеты однострочного текстового поля, и два метода, возвращающие содержимое этих полей — firstName() и lastName().

По умолчанию область заголовка диалогового окна содержит кнопку ?, служащую для получения подробной информации о назначении виджетов.

В нашем примере я решил пренебречь ею — для этого необходимо установить флаги окна, поэтому вторым параметром передаются флаги Qt::WindowTitleHint и Qt::WindowSystemMenuHint, первый устанавливает заголовок окна, а второй — добавляет системное меню с возможностью закрытия окна.

Модальное диалоговое окно всегда должно содержать кнопку Cancel (Отмена). Сигналы clicked() кнопок Ok и Cancel (Отмена) соединяются со слотами accept() и rejected() соответственно. Это делается для того, чтобы метод exec() возвращал при нажатии кнопки Ok значение QDialog::Accepted, а при нажатии на кнопку Cancel (Отмена) — значение QDialog::Rejected.

Модальное диалоговое окно блокирует родительский виджет. Блокировка снимается только при закрытии диалогового окна. Такое поведение оказывается проще при реализации, поскольку оно ограничивает свободу пользователя и снижает количество возможных проблем. Однако пользователи могут счесть это недостатком.

Немодальное диалоговое окно обладает в точности противоположным поведением по сравнению с модальным. Пользователь может взаимодействовать и с родительским виджетом, и с диалоговым окном, переключаясь между ними. Управлять подобной логикой взаимодействия сложнее. Но в замен пользователь получает свободу, которой ему могло не хватать в модальном варианте.

Выбор типа диалогового окна основывается на здравом смысле и относится к этапу юзабилити-тестирования. Мы этого вопроса касаться не станем. Рассмотрим лишь технику создания и тех, и других диалоговых окон с помощью Qt.

Класс диалогового окна

Реализуем простой класс диалогового окна. Именно его мы попробуем вызывать в модальном и немодальном режимах.

qt-easy-dialog

На нашем диалоговом окне мы разместили одно поле ввода и три кнопки: OK , Apply и Cancel .

Кнопка OK предназначена для подтверждения ввода с последующим закрытием окна. Этого мы добились, связав сигнал щелчка по кнопке со стандартным слотом QDialog::accept() .

Кнопка Apply так же предназначена для подтверждения ввода. Но предполагает продолжение работы с диалоговым окном. Для реализации такой логики мы предусмотрели сигнал applied() .

Последняя кнопка Cancel просто закрывает диалоговое окно. Больше ничего не происходит. Введенные данные отклоняются. Для этого мы используем слот QDialog::reject() .

Других кодов в QDialog не предусмотрено (кроме Accepted и Rejected ). Поэтому существует слот QDialog::done( int ) . Он закрывает окно и возвращает в качестве результата вызова указанное целочисленное значение.

Нажатие клавиши Esc в диалоговом окне приводит к вызову QDialog::reject() , а Enter связывается с кнопкой по умолчанию. Такой кнопкой становится либо первая добавленная кнопка (в нашем случае OK ), либо кнопка, для которой вызвана функция btn->setDefault( true ) .

Чтобы извлечь введенное значение в текстовое поле, мы предусмотрели константную функцию-член getInput() .

Реклама

Модальное диалоговое окно

Реализуем виджет, который будет использовать наше диалоговое окно:

qt-parent-widget

Виджет содержит текстовое поле и две кнопки. Первая предназначена для вызова модального диалогового окна, а вторая - для немодального. Сосредоточимся на первой.

Модальное диалоговое окно обеспечивает блокировку вызывающей функции с помощью вызова exec() (как у QApplication ). Это дает нам полное право создавать такой диалог в виде локальной переменной. Обращаю внимание, что в конструкторе диалогового окна мы передаем указать на виджет. Это обеспечивает необходимую привязку.

Мы должны не забыть привязать сигнал applied() нашего диалогового окна к специально созданному слоту onApplied() . В нем мы просто устанавливаем значение введенной строки в качестве значения текстового поля виджета.

Момент отображения диалогового окна соответствует строке с вызовом dlg.exec() . В качестве ответа возвращается код завершения работы окна. Единственный интересный для нас случай: QDialog::Accepted . Для него мы делаем то же самое, что и в слоте onApplied() .

Не забудьте убедиться, что родительский виджет становится неактивным, когда модальное диалоговое окно отображается.

Реклама

Немодальное диалоговое окно

Добавим реализацию слота onNonModalDemo() для вызова нашего диалогового окна в немодальном режиме:

Следует заметить, что для немодального диалогового окна мы завели отдельное поле класса в виджете. Это необходимо, поскольку немодальное окно не блокирует выполнение слота, поэтому локальная переменная оказалась бы уничтожена.

Для обработки ответа QDialog::Accepted мы делаем привязку к сигналу диалогового окна accepted() . Есть аналогичный сигнал для отрицательного ответа rejected() . А также для нашего собственного кода результата (на случай вызова слота done( int ) ): finished( int ) .

Важным отличием является то, что отображаем диалог мы не с помощью exec() , а путем вызова show() .

Освобождать указатель на немодальное диалоговое окно нам не нужно. Это произойдет автоматически при вызове деструктора родительского виджета. В этот же момент диалоговое окно закроется.

Если запустить немодальное диалоговое окно, то родительский виджет остается доступен. Например, мы можем открыть после этого еще и модальное диалоговое окно. Заметим, что в этом случае блокируется и родительский виджет, и немодальное диалоговое окно.

Выводы

A dialog window is a top-level window mostly used for short-term tasks and brief communications with the user. QDialogs may be modal or modeless. QDialogs can provide a return value, and they can have default buttons. QDialogs can also have a QSizeGrip in their lower-right corner, using setSizeGripEnabled().

Note that QDialog (and any other widget that has type Qt::Dialog ) uses the parent widget slightly differently from other classes in Qt. A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent's top-level widget (if it is not top-level itself). It will also share the parent's taskbar entry.

Use the overload of the QWidget::setParent() function to change the ownership of a QDialog widget. This function allows you to explicitly set the window flags of the reparented widget; using the overloaded function will clear the window flags specifying the window-system properties for the widget (in particular it will reset the Qt::Dialog flag).

Note: The parent relationship of the dialog does not imply that the dialog will always be stacked on top of the parent window. To ensure that the dialog is always on top, make the dialog modal. This also applies for child windows of the dialog itself. To ensure that child windows of the dialog stay on top of the dialog, make the child windows modal as well.

Modal Dialogs

A modal dialog is a dialog that blocks input to other visible windows in the same application. Dialogs that are used to request a file name from the user or that are used to set application preferences are usually modal. Dialogs can be application modal (the default) or window modal.

When an application modal dialog is opened, the user must finish interacting with the dialog and close it before they can access any other window in the application. Window modal dialogs only block access to the window associated with the dialog, allowing the user to continue to use other windows in an application.

The most common way to display a modal dialog is to call its exec() function. When the user closes the dialog, exec() will provide a useful return value. To close the dialog and return the appropriate value, you must connect a default button, e.g. an OK button to the accept() slot and a Cancel button to the reject() slot. Alternatively, you can call the done() slot with Accepted or Rejected .

An alternative is to call setModal(true) or setWindowModality(), then show(). Unlike exec(), show() returns control to the caller immediately. Calling setModal(true) is especially useful for progress dialogs, where the user must have the ability to interact with the dialog, e.g. to cancel a long running operation. If you use show() and setModal(true) together to perform a long operation, you must call QCoreApplication::processEvents() periodically during processing to enable the user to interact with the dialog. (See QProgressDialog.)

Modeless Dialogs

A modeless dialog is a dialog that operates independently of other windows in the same application. Find and replace dialogs in word-processors are often modeless to allow the user to interact with both the application's main window and with the dialog.

Modeless dialogs are displayed using show(), which returns control to the caller immediately.

If you invoke the show() function after hiding a dialog, the dialog will be displayed in its original position. This is because the window manager decides the position for windows that have not been explicitly placed by the programmer. To preserve the position of a dialog that has been moved by the user, save its position in your closeEvent() handler and then move the dialog to that position, before showing it again.

Default Button

A dialog's default button is the button that's pressed when the user presses Enter (Return). This button is used to signify that the user accepts the dialog's settings and wants to close the dialog. Use QPushButton::setDefault(), QPushButton::isDefault() and QPushButton::autoDefault() to set and control the dialog's default button.

Escape Key

If the user presses the Esc key in a dialog, QDialog::reject() will be called. This will cause the window to close: The close event cannot be ignored.

Extensibility

Extensibility is the ability to show the dialog in two ways: a partial dialog that shows the most commonly used options, and a full dialog that shows all the options. Typically an extensible dialog will initially appear as a partial dialog, but with a More toggle button. If the user presses the More button down, the dialog is expanded. The Extension Example shows how to achieve extensible dialogs using Qt.

Return Value (Modal Dialogs)

Modal dialogs are often used in situations where a return value is required, e.g. to indicate whether the user pressed OK or Cancel. A dialog can be closed by calling the accept() or the reject() slots, and exec() will return Accepted or Rejected as appropriate. The exec() call returns the result of the dialog. The result is also available from result() if the dialog has not been destroyed.

In order to modify your dialog's close behavior, you can reimplement the functions accept(), reject() or done(). The closeEvent() function should only be reimplemented to preserve the dialog's position or to override the standard close or reject behavior.

A dialog window is a top-level window mostly used for short-term tasks and brief communications with the user. QDialogs may be modal or modeless. QDialogs can provide a return value, and they can have default buttons. QDialogs can also have a QSizeGrip in their lower-right corner, using setSizeGripEnabled().

Note that QDialog (and any other widget that has type Qt::Dialog ) uses the parent widget slightly differently from other classes in Qt. A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent's top-level widget (if it is not top-level itself). It will also share the parent's taskbar entry.

Use the overload of the QWidget::setParent() function to change the ownership of a QDialog widget. This function allows you to explicitly set the window flags of the reparented widget; using the overloaded function will clear the window flags specifying the window-system properties for the widget (in particular it will reset the Qt::Dialog flag).

Note: The parent relationship of the dialog does not imply that the dialog will always be stacked on top of the parent window. To ensure that the dialog is always on top, make the dialog modal. This also applies for child windows of the dialog itself. To ensure that child windows of the dialog stay on top of the dialog, make the child windows modal as well.

Modal Dialogs

A modal dialog is a dialog that blocks input to other visible windows in the same application. Dialogs that are used to request a file name from the user or that are used to set application preferences are usually modal. Dialogs can be application modal (the default) or window modal.

When an application modal dialog is opened, the user must finish interacting with the dialog and close it before they can access any other window in the application. Window modal dialogs only block access to the window associated with the dialog, allowing the user to continue to use other windows in an application.

The most common way to display a modal dialog is to call its exec() function. When the user closes the dialog, exec() will provide a useful return value. To close the dialog and return the appropriate value, you must connect a default button, e.g. an OK button to the accept() slot and a Cancel button to the reject() slot. Alternatively, you can call the done() slot with Accepted or Rejected .

An alternative is to call setModal(true) or setWindowModality(), then show(). Unlike exec(), show() returns control to the caller immediately. Calling setModal(true) is especially useful for progress dialogs, where the user must have the ability to interact with the dialog, e.g. to cancel a long running operation. If you use show() and setModal(true) together to perform a long operation, you must call QCoreApplication::processEvents() periodically during processing to enable the user to interact with the dialog. (See QProgressDialog.)

Modeless Dialogs

A modeless dialog is a dialog that operates independently of other windows in the same application. Find and replace dialogs in word-processors are often modeless to allow the user to interact with both the application's main window and with the dialog.

Modeless dialogs are displayed using show(), which returns control to the caller immediately.

If you invoke the show() function after hiding a dialog, the dialog will be displayed in its original position. This is because the window manager decides the position for windows that have not been explicitly placed by the programmer. To preserve the position of a dialog that has been moved by the user, save its position in your closeEvent() handler and then move the dialog to that position, before showing it again.

Default Button

A dialog's default button is the button that's pressed when the user presses Enter (Return). This button is used to signify that the user accepts the dialog's settings and wants to close the dialog. Use QPushButton::setDefault(), QPushButton::isDefault() and QPushButton::autoDefault() to set and control the dialog's default button.

Escape Key

If the user presses the Esc key in a dialog, QDialog::reject() will be called. This will cause the window to close: The close event cannot be ignored.

Extensibility

Extensibility is the ability to show the dialog in two ways: a partial dialog that shows the most commonly used options, and a full dialog that shows all the options. Typically an extensible dialog will initially appear as a partial dialog, but with a More toggle button. If the user presses the More button down, the dialog is expanded. The Extension Example shows how to achieve extensible dialogs using Qt.

Return Value (Modal Dialogs)

Modal dialogs are often used in situations where a return value is required, e.g. to indicate whether the user pressed OK or Cancel. A dialog can be closed by calling the accept() or the reject() slots, and exec() will return Accepted or Rejected as appropriate. The exec() call returns the result of the dialog. The result is also available from result() if the dialog has not been destroyed.

In order to modify your dialog's close behavior, you can reimplement the functions accept(), reject() or done(). The closeEvent() function should only be reimplemented to preserve the dialog's position or to override the standard close or reject behavior.

Класс QDialog является базовым для всех диалоговых окон, представленных в классовой иерархии Qt. Хотя диалоговое окно можно создавать при помощи любого виджета, сделав его виджетом верхнего уровня, тем не менее, удобнее воспользоваться классом QDialog, который предоставляет ряд возможностей, необходимых всем диалоговым окнам. Диалоговые окна подразделяются на две группы:

Режим модальности и немодальности можно установить и узнать при помощи методов QDialog::setModal() и QDialog::isModal() соответственно.

При установке true соответствует модальному режиму, a false — немодальному.

Модальные диалоговые окна

В этих случаях модальный диалог — идеальное средство для обращения внимания пользователя на себя.

Для блокировки приложения запускается цикл события только для диалогового окна, а события клавиатуры, мыши и других элементов приложения просто игнорируются. Этот цикл запускается вызовом слота exec(), который возвращает значение целого типа после закрытия диалогового окна. Это значение информирует о нажатой кнопке и может принимать значения QDialog::Accepted или QDialog::Rejected, соответствующие кнопкам Ok и Cancel (Отмена). Типичным примером модального окна является напоминание пользователю, перед закрытием приложения, о необходимости сохранения документа. В момент отображения этого окна возможность работы с самим приложением должна быть заблокирована. Принцип вызова модального диалогового окна примерно следующий:

Немодальные диалоговые окна

Немодальные диалоговые окна ведут себя как нормальные виджеты, не прерывая, при своем появлении, работу приложения. На первый взгляд может показаться, что применение немодальных диалоговых окон имеет больше смысла, так как в этом случае пользователь обладает большей свободой в своих действиях. Но, на самом деле, большинство приложений нуждается в остановке и ожидании решения пользователя для возобновления своих дальнейших действий.

Немодальное окно может быть отображено с помощью метода show(), также как и для обычного виджета. Метод show() не возвращает никаких значений и не останавливает выполнение всей программы. Метод hide() позволяет сделать окно невидимым. Этим свойством можно воспользоваться, и в этом случае не требуется создавать каждый раз объект диалогового окна, а при закрытии удалять его из памяти. Можно ограничиться вызовом методов show() и hide(), что даст возможность отобразить диалоговое окно, на том же месте, на котором оно было свернуто. Немодальные диалоговые окна необходимо снабжать кнопкой Close (Закрыть) для того, чтобы дать возможность пользователю закрыть его.

Читайте также: