Creating a dialog box in PyQt
Write a Python program that creates a simple dialog box that displays a message or input form when a button is clicked using PyQt.
From doc.qt.io:
QApplication Class: The QApplication class manages the GUI application's control flow and main settings.
QMainWindow Class: The QMainWindow class provides a main application window.
QPushButton: The push button, or command button, is perhaps the most commonly used widget in any graphical user interface. Push (click) a button to command the computer to perform some action, or to answer a question. Typical buttons are OK, Apply, Cancel, Close, Yes, No and Help.
QDialog Class: The QDialog class is the base class of dialog windows.
QVBoxLayout Class: This class is used to construct vertical box layout objects.
QLabel Class: The QLabel widget provides a text or image display.
QWidget: The QWidget class is the base class of all user interface objects.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- Import the necessary modules.
- Create a "QMainWindow" (MyWindow) with a central widget.
- Inside the central widget, we create a 'QPushButton' (dialog_button) labeled "Show Dialog" and connect its clicked signal to the show_dialog method.
- In the "show_dialog()" method, we create a QDialog instance (dialog) and set its title.
- Create a "QLabel" (label) with the message we want to display in the dialog.
- Create a QVBoxLayout for the dialog and add the label to it.
- Set the dialog layout using "dialog.setLayout".
- When the "Show Dialog" button is clicked, the show_dialog method is called, which displays the dialog as a modal dialog using “dialog.exec_()”. To interact with the main window again, the dialog must be closed.
Output:
Flowchart:
Python Code Editor:
Previous: Customizing widget behavior with PyQt event handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics