[Python combat basics] How to create a menu bar in PyQt6

1. The actual combat scene

Actual combat scenario: how PyQt6 creates a menu bar

2. Main points of knowledge

  • file read and write

  • Basic grammar

  • PyQt6

  • sys

Three, rookie combat

A menu bar is common in GUI applications and is a set of commands located in various menus. (Mac OS treats the menu bar differently, to get a similar result, we can add the following line: menubar.setNativeMenuBar(False)

import sys
from PyQt6.QtWidgets import QMainWindow, QApplication
from PyQt6.QtGui import QIcon, QAction


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        exitAct = QAction(QIcon('exit.png'), '&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(QApplication.instance().quit)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Simple menu')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

In the door-to-door example, a menu bar with a menu is created. This menu command terminates the application and is also bound to a shortcut key  Ctrl+Q. A status bar is also created in the example.

exitAct = QAction(QIcon('exit.png'), '&Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')

QAction Is an abstract class for behavior, including menu bars, toolbars, or custom keyboard shortcuts. In the three lines above, a behavior with a specific icon and an 'Exit' label is created. Additionally, a shortcut is defined for this behavior. The third line creates a status tip, which is displayed in the status bar when we hover the mouse pointer over the menu item.

exitAct.triggered.connect(QApplication.instance().quit)

When the specified behavior is selected, a signal is fired that connects the  QApplication component's exit action, which terminates the application.

menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)

menuBar method to create a menu bar, then use to  addMenu create a file menu, use to  addAction create a behavior.

Guess you like

Origin blog.csdn.net/qq_39816613/article/details/126829132