Python PyQt menu example
Write a Python program that creates an application with a menu. When we choose menu items, a specific message appears.
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.
QMenu Class: The QMenu class provides a menu widget for use in menu bars, context menus, and other popup menus.
QAction Class: The QAction class provides an abstraction for user commands that can be added to different user interface components.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- Import the necessary modules from PyQt5.
- Create a custom "QMainWindow" class named "MenuApp" that builds the main application window.
- Set up a menu bar and created a menu called "File."
- Inside the "File" menu, we create actions for menu items like "Open," "Save," and "Exit."
- Connect each menu action to a function (self.open_file, self.save_file, self.close) that does something when the menu items are selected.
- In the main() function, we create the PyQt application, instantiate the "MenuApp" class, and show the main window.
Output:
Open file menu item selected Save file menu item selected![]()
Flowchart:


Go to:
Previous: Python PyQt checkbox example.
Next: Python PyQt keyboard shortcut example.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.