How to create a menu bar and toolbar in PyQt5?

In PyQt5, you can use QMenuBar to create a menu bar and QToolBar to create a toolbar. Here is a simple example:

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

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

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

        # 创建菜单
        file_menu = menu_bar.addMenu('File')
        edit_menu = menu_bar.addMenu('Edit')

        # 在菜单中添加动作
        new_action = QAction('New', self)
        file_menu.addAction(new_action)

        save_action = QAction('Save', self)
        file_menu.addAction(save_action)

        cut_action = QAction('Cut', self)
        edit_menu.addAction(cut_action)

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

        # 创建工具栏
        tool_bar = QToolBar(self)
        self.addToolBar(tool_bar)

        # 在工具栏中添加动作
        tool_bar.addAction(new_action)
        tool_bar.addAction(save_action)
        tool_bar.addAction(cut_action)
        tool_bar.addAction(copy_action)

        self.setWindowTitle('Menu and Toolbar Example')
        self.show()

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

In this example, we constructed a main window with a menu bar and a toolbar. We began by utilizing the menuBar() method to obtain the window’s menu bar, and then used the addMenu() method to add menus to the menu bar. Finally, we used the addAction() method to incorporate actions within the menu.

We also created a toolbar and added it to the window using the addToolBar() method. Then we added actions to the toolbar using the addAction() method.

Finally, we add all actions to the menu and toolbar, and display the window. Upon running the program, you will see a main window with a menu bar and toolbar.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds