QDialog¶
- PyQt6.QtWidgets.QDialog
Inherits from QWidget.
Inherited by QAbstractPrintDialog, QColorDialog, QErrorMessage, QFileDialog, QFontDialog, QInputDialog, QMessageBox, QPageSetupDialog, QPrintPreviewDialog, QProgressDialog, QWizard.
Description¶
The QDialog class is the base class of dialog windows.
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 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 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 ApplicationModal (the default) or WindowModal.
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 open() function. Alternatively, you can call setModal(true) or setWindowModality(), and then show(). In both cases, once the dialog is displayed, the control is immediately returned to the caller. You must connect to the finished signal to know when the dialog is closed and what its return value is. Alternatively, you can connect to the accepted and rejected signals.
When implementing a custom dialog, to close the dialog and return an appropriate value, connect a default button, for example, 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
.
If you show the modal dialog to perform a long-running operation, it is recommended to perform the operation in a background worker thread, so that it does not interfere with the GUI thread.
Warning: When using open() or show(), the modal dialog should not be created on the stack, so that it does not get destroyed as soon as the control returns to the caller.
Note: There is a way to show a modal dialog in a blocking mode by calling exec(). In this case, the control returns to the GUI thread only when the dialog is closed. However, such approach is discouraged, because it creates a nested event loop, which is not fully supported by some platforms.
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.
Escape Key¶
If the user presses the Esc key in a dialog, reject() will be called. This will cause the window to close: The QCloseEvent cannot be ignore().
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.
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.
Code Examples¶
A modal dialog:
# void EditorWindow::countWords()
# {
# WordCountDialog dialog(this);
# dialog.setWordCount(document().wordCount());
# dialog.exec();
# }
A modeless dialog:
# void EditorWindow::find()
# {
# if (!findDialog) {
# findDialog = new FindDialog(this);
# connect(findDialog, &FindDialog::findNext,
# this, &EditorWindow::findNext);
# }
# findDialog->show();
# findDialog->raise();
# findDialog->activateWindow();
# }
A dialog with an extension:
# This code needs porting to Python.
# /****************************************************************************
# **
# ** Copyright (C) 2016 The Qt Company Ltd.
# ** Contact: https://www.qt.io/licensing/
# **
# ** This file is part of the documentation of the Qt Toolkit.
# **
# ** $QT_BEGIN_LICENSE:BSD$
# ** Commercial License Usage
# ** Licensees holding valid commercial Qt licenses may use this file in
# ** accordance with the commercial license agreement provided with the
# ** Software or, alternatively, in accordance with the terms contained in
# ** a written agreement between you and The Qt Company. For licensing terms
# ** and conditions see https://www.qt.io/terms-conditions. For further
# ** information use the contact form at https://www.qt.io/contact-us.
# **
# ** BSD License Usage
# ** Alternatively, you may use this file under the terms of the BSD license
# ** as follows:
# **
# ** "Redistribution and use in source and binary forms, with or without
# ** modification, are permitted provided that the following conditions are
# ** met:
# ** * Redistributions of source code must retain the above copyright
# ** notice, this list of conditions and the following disclaimer.
# ** * Redistributions in binary form must reproduce the above copyright
# ** notice, this list of conditions and the following disclaimer in
# ** the documentation and/or other materials provided with the
# ** distribution.
# ** * Neither the name of The Qt Company Ltd nor the names of its
# ** contributors may be used to endorse or promote products derived
# ** from this software without specific prior written permission.
# **
# **
# ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
# **
# ** $QT_END_LICENSE$
# **
# ****************************************************************************/
# #include <QtWidgets>
# typedef QDialog WordCountDialog;
# typedef QDialog FindDialog;
# #define this 0
# #define setWordCount(x) isVisible()
# QString tr(const char *text)
# {
# return QApplication::translate(text, text);
# }
# class EditorWindow : public QMainWindow
# {
# public:
# void find();
# void countWords();
# private:
# FindDialog *findDialog;
# };
# #! [0]
# void EditorWindow::find()
# {
# if (!findDialog) {
# findDialog = new FindDialog(this);
# connect(findDialog, &FindDialog::findNext,
# this, &EditorWindow::findNext);
# }
# findDialog->show();
# findDialog->raise();
# findDialog->activateWindow();
# }
# #! [0]
# #! [1]
# void EditorWindow::countWords()
# {
# WordCountDialog dialog(this);
# dialog.setWordCount(document().wordCount());
# dialog.exec();
# }
# #! [1]
# inline bool boo()
# {
# QMessageBox::information(this, "Application name",
# "Unable to find the user preferences file.\n"
# "The factory default will be used instead.");
# QString filename;
# if (QFile::exists(filename) &&
# QMessageBox::question(
# this,
# tr("Overwrite File? -- Application Name"),
# tr("A file called %1 already exists."
# "Do you want to overwrite it?")
# .arg(filename),
# tr("&Yes"), tr("&No"),
# QString(), 0, 1))
# return false;
# switch(QMessageBox::warning(this, "Application name",
# "Could not connect to the <mumble> server.\n"
# "This program can't function correctly "
# "without the server.\n\n",
# "Retry",
# "Quit", 0, 0, 1)) {
# case 0: // The user clicked the Retry again button or pressed Enter
# // try again
# break;
# case 1: // The user clicked the Quit or pressed Escape
# // exit
# break;
# }
# switch(QMessageBox::information(this, "Application name here",
# "The document contains unsaved changes\n"
# "Do you want to save the changes before exiting?",
# "&Save", "&Discard", "Cancel",
# 0, // Enter == button 0
# 2)) { // Escape == button 2
# case 0: // Save clicked or Alt+S pressed or Enter pressed.
# // save
# break;
# case 1: // Discard clicked or Alt+D pressed
# // don't save but exit
# break;
# case 2: // Cancel clicked or Escape pressed
# // don't exit
# break;
# }
# switch(QMessageBox::warning(this, "Application name here",
# "Could not save the user preferences,\n"
# "because the disk is full. You can delete\n"
# "some files and press Retry, or you can\n"
# "abort the Save Preferences operation.",
# QMessageBox::Retry | QMessageBox::Default,
# QMessageBox::Abort | QMessageBox::Escape)) {
# case QMessageBox::Retry: // Retry clicked or Enter pressed
# // try again
# break;
# case QMessageBox::Abort: // Abort clicked or Escape pressed
# // abort
# break;
# }
# QString errorDetails;
# QMessageBox::critical(0, "Application name here",
# QString("An internal error occurred. Please ") +
# "call technical support at 1234-56789 and report\n"+
# "these numbers:\n\n" + errorDetails +
# "\n\nApplication will now exit.");
# QMessageBox::about(this, "About <Application>",
# "<Application> is a <one-paragraph blurb>\n\n"
# "Copyright 1991-2003 Such-and-such. "
# "<License words here.>\n\n"
# "For technical support, call 1234-56789 or see\n"
# "http://www.such-and-such.com/Application/\n");
# {
# // saving the file
# QMessageBox mb("Application name here",
# "Saving the file will overwrite the original file on the disk.\n"
# "Do you really want to save?",
# QMessageBox::Information,
# QMessageBox::Yes | QMessageBox::Default,
# QMessageBox::No,
# QMessageBox::Cancel | QMessageBox::Escape);
# mb.setButtonText(QMessageBox::Yes, "Save");
# mb.setButtonText(QMessageBox::No, "Discard");
# switch(mb.exec()) {
# case QMessageBox::Yes:
# // save and exit
# break;
# case QMessageBox::No:
# // exit without saving
# break;
# case QMessageBox::Cancel:
# // don't save and don't exit
# break;
# }
# }
# {
# // hardware failure
# #! [2]
# QMessageBox mb("Application Name",
# "Hardware failure.\n\nDisk error detected\nDo you want to stop?",
# QMessageBox::Question,
# QMessageBox::Yes | QMessageBox::Default,
# QMessageBox::No | QMessageBox::Escape,
# QMessageBox::NoButton);
# if (mb.exec() == QMessageBox::No) {
# // try again
# #! [2]
# }
# }
# }
# inline void moo()
# {
# int numFiles;
# #! [3]
# QProgressDialog progress("Copying files...", "Abort Copy", 0, numFiles, this);
# progress.setWindowModality(Qt::WindowModal);
# for (int i = 0; i < numFiles; i++) {
# progress.setValue(i);
# if (progress.wasCanceled())
# break;
# //... copy one file
# }
# progress.setValue(numFiles);
# #! [3]
# }
# class Operation : public QObject
# {
# public:
# Operation(QObject *parent);
# void perform();
# void cancel();
# private:
# int steps;
# QProgressDialog *pd;
# QTimer *t;
# };
# #! [4]
# // Operation constructor
# Operation::Operation(QObject *parent)
# : QObject(parent), steps(0)
# {
# pd = new QProgressDialog("Operation in progress.", "Cancel", 0, 100);
# connect(pd, &QProgressDialog::canceled, this, &Operation::cancel);
# t = new QTimer(this);
# connect(t, &QTimer::timeout, this, &Operation::perform);
# t->start(0);
# }
# #! [4] #! [5]
# void Operation::perform()
# {
# pd->setValue(steps);
# //... perform one percent of the operation
# steps++;
# if (steps > pd->maximum())
# t->stop();
# }
# #! [5] #! [6]
# void Operation::cancel()
# {
# t->stop();
# //... cleanup
# }
# #! [6]
# int main()
# {
# }
By setting the sizeConstraint() property of the dialog’s layout to SetFixedSize, the dialog will not be resizable by the user, and will automatically shrink when the extension gets hidden.
See also
QDialogButtonBox, QTabWidget, QWidget, QProgressDialog, Standard Dialogs Example.
Enums¶
- DialogCode
The value returned by a modal dialog.
Member
Value
Description
Accepted TODO
TODO
Rejected TODO
TODO
Methods¶
- __init__(parent: QWidget = None, flags: WindowType = Qt.WindowFlags())
Constructs a dialog with parent parent.
A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent. It will also share the parent’s taskbar entry.
The widget flags f are passed on to the QWidget constructor. If, for example, you don’t want a What’s This button in the title bar of the dialog, pass WindowTitleHint | WindowSystemMenuHint in f.
See also
- accept()
Hides the modal dialog and sets the result code to
Accepted
.
- closeEvent(QCloseEvent)
TODO
- contextMenuEvent(QContextMenuEvent)
TODO
- done(int)
Closes the dialog and sets its result code to r. The finished signal will emit r; if r is Accepted or Rejected, the accepted or the rejected signals will also be emitted, respectively.
If this dialog is shown with exec(), also causes the local event loop to finish, and exec() to return r.
As with close(), deletes the dialog if the WA_DeleteOnClose flag is set. If the dialog is the application’s main widget, the application terminates. If the dialog is the last window closed, the lastWindowClosed signal is emitted.
See also
- exec() int
Shows the dialog as a modal dialog, blocking until the user closes it. The function returns a DialogCode result.
If the dialog is ApplicationModal, users cannot interact with any other window in the same application until they close the dialog. If the dialog is ApplicationModal, only interaction with the parent window is blocked while the dialog is open. By default, the dialog is application modal.
Note: Avoid using this function; instead, use
open()
. Unlike , open() is asynchronous, and does not spin an additional event loop. This prevents a series of dangerous bugs from happening (e.g. deleting the dialog’s parent while the dialog is open via ). When using open() you can connect to the finished signal of QDialog to be notified when the dialog is closed.
- isSizeGripEnabled() bool
TODO
- keyPressEvent(QKeyEvent)
TODO
- minimumSizeHint() QSize
TODO
- open()
Shows the dialog as a window modal dialog, returning immediately.
- reject()
Hides the modal dialog and sets the result code to
Rejected
.
- resizeEvent(QResizeEvent)
TODO
- result() int
In general returns the modal dialog’s result code,
Accepted
orRejected
.Note: When called on a QMessageBox instance, the returned value is a value of the StandardButtons enum.
Do not call this function if the dialog was constructed with the WA_DeleteOnClose attribute.
See also
- setModal(bool)
TODO
- setResult(int)
Sets the modal dialog’s result code to i.
Note: We recommend that you use one of the values defined by DialogCode.
See also
- setSizeGripEnabled(bool)
See also
- setVisible(bool)
TODO
- showEvent(QShowEvent)
TODO
- sizeHint() QSize
TODO
Signals¶
- accepted()
This signal is emitted when the dialog has been accepted either by the user or by calling accept() or done() with the Accepted argument.
Note that this signal is not emitted when hiding the dialog with hide() or setVisible()(false). This includes deleting the dialog while it is visible.
- finished(int)
This signal is emitted when the dialog’s result code has been set, either by the user or by calling done(), accept(), or reject().
Note that this signal is not emitted when hiding the dialog with hide() or setVisible()(false). This includes deleting the dialog while it is visible.
- rejected()
This signal is emitted when the dialog has been rejected either by the user or by calling reject() or done() with the Rejected argument.
Note that this signal is not emitted when hiding the dialog with hide() or setVisible()(false). This includes deleting the dialog while it is visible.