PyQt5入门(二)——菜单、工具、状态栏

此总结主要参考下面这篇文章:PyQt5菜单和工具栏

状态栏、菜单栏和工具栏是QWidget类没有的,文中出现的self默认继承了QMainWindow的类

1. 状态栏

from PyQt5.QtWidgets import QMainWindow # 这里只导入与内容直接相关的库

self.statusBar().showMessage('Ready')
# 默认前面已经继承了QMainWindow的类
# 先调用statusBar()创建一个状态栏,后续调用返回的状态栏对象,在状态栏上显示一条消息

2. 菜单栏

from PyQt5.QtWidgets import QAction # 事件,与菜单栏非直接相关,但是让每个菜单栏有意义必须有这个
from PyQt5.QtWidgets import qApp # 与菜单栏无关,只是这里的示例用到了它
from PyQt5.QtGui import QIcon # 非必须只是一个点缀

self.statusBar()

exitAction = QAction(QIcon('web.png'),'&Exit',self) #这里的‘&’应该是在右侧的字母下添加下划线,但是我这里运行之后和不加没区别
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')

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

3.工具栏

self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
# 下面这么写也是OK的,但是写成类似上一个示例是不行的
# toolbar = self.addToolBar('Exit')
# toolbar.addAction(exitAction)

综合上述功能得到如下示例:

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


class Example(QMainWindow):

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

        self.initUI()

    def initUI(self):
        # 创建事件
        exitAction = QAction('E&xit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        # 创建一个菜单栏
        menubar = self.menuBar()
        # 添加菜单
        fileMenu = menubar.addMenu('File')
        # 添加事件
        fileMenu.addAction(exitAction)

        # 添加一个工具栏
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(exitAction)

        self.statusBar().showMessage('Ready')

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Menubar')
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

猜你喜欢

转载自blog.csdn.net/qq_34710142/article/details/80825129