PyQt - QDialog Widget



The QDialog widget in PyQt serves as a base class for dialog windows. We can create custom dialog boxes with various functionalities such as input forms, message boxes, and more. QDialog inherits from QWidget which makes it flexible and can be customized for different use cases.

QDialog Widget: Methods and Descriptions

Method Description
exec() Executes the dialog synchronously.
open() Opens the dialog non-modally.
accept() Emits the accepted signal and closes the dialog.
reject() Emits the rejected signal and closes the dialog.
setModal(bool) Sets whether the dialog is modal.
result() Returns the result of the dialog.
setDefaultButton(QPushButton) Sets the default button for the dialog.
setFixedSize(int, int) Sets the fixed size of the dialog.
setSizeGripEnabled(bool) Sets whether the size grip is enabled.
setWindowModality(Qt.WindowModality) Sets the window modality for the dialog.

Examples

Example 1: Simple Message Box

In the below example, we create a simple message box using QMessageBox. We then set the text of the message box to "Hello, PyQt!" and execute it using exec() function.

import sys
from PyQt6.QtWidgets import QApplication, QDialog, QMessageBox

class SimpleMessageBox(QDialog):
   def __init__(self):
      super().__init__()
      self.setWindowTitle("Simple Message Box")

      msg_box = QMessageBox()
      msg_box.setText("Hello, PyQt!")
      msg_box.exec()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   dialog = SimpleMessageBox()
   dialog.exec()
   sys.exit(app.exec())

Output

The above code produces the following output −

pyqt dialogwidget example 1

Example 2: Input Dialog

In the below example, we implement how to create an input dialog using QInputDialog. When we click the button a dialog asks the user to enter their name. The entered text is printed on the console.

import sys
from PyQt6.QtWidgets import QApplication, QDialog, QLineEdit, QVBoxLayout, QPushButton, QInputDialog

class InputDialog(QDialog):
   def __init__(self):
      super().__init__()
      self.setWindowTitle("Input Dialog")

      layout = QVBoxLayout()
      self.setLayout(layout)

      self.button = QPushButton("Get Input", self)
      self.button.clicked.connect(self.get_input)
      layout.addWidget(self.button)

   def get_input(self):
      text, ok = QInputDialog.getText(self, "Input Dialog", "Enter your name:")
      if ok:
         print("Your name is:", text)

if __name__ == "__main__":
   app = QApplication(sys.argv)
   dialog = InputDialog()
   dialog.exec()
   sys.exit(app.exec())

Output

The above code produces the following output −

pyqt qdialogwidget example 2
Advertisements