Creating a Simple Menu in PyQt | Python GUI Tutorial #2

Posted by


In this tutorial, we will continue our exploration of creating a simple menu in PyQt. This is the second part of a series, so make sure you check out the first part if you haven’t already. In this part, we will be creating a basic menu with some additional functionality.

To get started, make sure you have PyQt installed on your system. If you don’t have it installed, you can do so by running the following command:

pip install PyQt5

Once you have PyQt installed, you can create a new Python file and import the necessary modules:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QMenu

Next, create a class for our main window:

class SimpleMenu(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Simple Menu')
        self.setGeometry(100, 100, 300, 200)

        self.createMenu()

    def createMenu(self):
        menu_bar = self.menuBar()

        file_menu = menu_bar.addMenu('File')

        exit_action = QAction('Exit', self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        edit_menu = menu_bar.addMenu('Edit')

        copy_action = QAction('Copy', self)
        edit_menu.addAction(copy_action)

        paste_action = QAction('Paste', self)
        edit_menu.addAction(paste_action)

        view_menu = menu_bar.addMenu('View')

        zoom_in_action = QAction('Zoom In', self)
        view_menu.addAction(zoom_in_action)

        zoom_out_action = QAction('Zoom Out', self)
        view_menu.addAction(zoom_out_action)

In this code, we have created a SimpleMenu class that inherits from QMainWindow. In the initUI method, we set the window title and geometry, and then call the createMenu method to create the menu.

In the createMenu method, we create a menu bar using self.menuBar(). We then add three menus – File, Edit, and View – to the menu bar using menu_bar.addMenu(). For each menu, we create QAction objects for the actions of the menu, connect the triggered signal of the action to a slot (in this case, self.close to exit the application), and add the action to the menu using menu.addAction().

Finally, we need to create an instance of the SimpleMenu class and run the application:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = SimpleMenu()
    window.show()
    sys.exit(app.exec_())

Now you can run the Python script, and you should see a simple window with a menu bar containing File, Edit, and View menus. Each menu should have corresponding actions that you can click on.

That’s it for this tutorial! In the next part, we will add functionality to the Edit menu actions. Stay tuned for more PyQt tutorials!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x