PyQt5学习记录(2)---QMainWindow菜单栏、状态栏和工具栏

本文详细介绍QMainWindow组件的使用方法,包括状态栏、菜单栏及工具栏的创建与配置过程,并提供示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

QMainWindow

QMainWindow是继承自QWidget,提供一个应用程序的主窗口。通过QMainWindow你可以添加自己的QToolBarsQDockWidgetsQMenuBarQStatusBar等。见下图:

所以如果我们写程序的话,主窗口一般都是继承QMainWindow,这个有点类似android里的Activity的意思。接下来我们就对最下面的状态栏(StatusBar)、最上面的菜单栏(MenuBar)、以及工具栏(ToolBars)做单独的说明.

状态栏(StatusBar)

源码如下:

#coding=utf-8
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication

class Example1(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        pass

    def initUI(self):
        self.statusBar().showMessage('Reday')
        self.setGeometry(300, 300, 450, 450)
        self.setWindowTitle('QMainWindow的状态栏demo')
        self.show()
        pass

def main1():
    app = QApplication(sys.argv)
    example = Example1()
    sys.exit(app.exec_())
    pass

if __name__ == '__main__':
    main1()

效果如下所示:

核心提示:通过statusBar()让QMainWindow创建一个状态栏,然后showMessage打印信息,之后再调statusBar将直接返回这个状态栏对象.

菜单栏(MenuBar)

一个应用程序可以有很多个菜单(横向的),每个菜单里有很多个Action(竖排的)。
源码如下:

#coding=utf-8
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenuBar, QAction, qApp
from PyQt5.QtGui import QIcon

# 菜单栏
class Example2(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        pass

    def initUI(self):
        self.statusBar() #创建一个空的状态栏
        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('File')

        #给menu创建一个Action
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctr+Q')
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(qApp.quit)

        #将这个Action添加到fileMenu上
        fileMenu.addAction(exitAction)

        self.setWindowTitle('QMainWindow的菜单栏的显示')
        self.setGeometry(300, 300, 450, 450)
        self.show()
        pass

def main2():
    app = QApplication(sys.argv)
    example = Example2()
    sys.exit(app.exec_())
    pass

if __name__ == '__main__':
    main2()

运行效果:

要点解释

  1. 在Mac上要加menubar.setNativeMenuBar(False),否则很可能不显示。这是因为Mac上的菜单栏不在应用程序的顶部,而是在整个桌面的顶部。加上这句话后显示的是Windows上的样式。
  2. 一个Menu必须要有一个Action才会显示,至少在Mac上是这样。
  3. Menu的关键字FileView,系统会自动给你加一些Action。
  4. Action的关键字为Exit时,同样不显示。下面是Mac上把menubar.setNativeMenuBar(False)去掉,把Action的关键字改成其他的效果.
  5. exitAction.triggered.connect(qApp.quit)的效果和exitAction.triggered.connect(QCoreApplication.instance().exit)效果是一样的,可以看qApp实际是一个宏。
  6. Action的信号是triggered, QPushButton的信号是clicked
  7. 在Mac上设置的退出快捷键好像没有效果。

工具栏ToolBar

在菜单栏里可以把所有的按钮都集中进来,但是最常用的按钮可以放在工具栏,即菜单栏的下方。

#coding=utf-8
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenuBar, QAction, qApp
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QCoreApplication

class Example3(QMainWindow):

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

    def initUI(self):
        exitAction = QAction(QIcon('exit.png'), '退出吧宝宝', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        self.toolbar = self.addToolBar('Exit123')
        self.toolbar.addAction(exitAction)
        self.toolbar.addAction(QIcon('exit.png'), '翻滚')

        self.setGeometry(300, 300, 450, 450)
        self.setWindowTitle('QMainWindow的ToolBar')
        self.show()
        pass

def main3():
    app = QApplication(sys.argv)
    example = Example3()
    sys.exit(app.exec_())
    pass

if __name__ == '__main__':
    main3()

效果如下:

要点解释

  1. 通过self.addToolBar('Exit')创建一个ToolBar,一个ToolBar可以加多个Action,默认是横向排列的。这里的Exit仅仅是标识TooBar,因为一个QMainWindow也可以有多个ToolBar。如下代码展示:
    self.toolbar = self.addToolBar('Exit123')
        self.toolbar.addAction(exitAction)
        self.toolbar.addAction(QIcon('exit.png'), '翻滚')

        self.toolbar2 = self.addToolBar('Exit456')
        self.toolbar2.addAction(exitAction)
        self.toolbar2.addAction(QIcon('exit.png'), '翻滚')

效果如下:

状态栏、工具栏、菜单栏综合练习

代码如下:

#coding=utf-8
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenuBar, QAction, qApp, QTextEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QCoreApplication

class Example4(QMainWindow):

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

    def initUI(self):
        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)

        # 创建一个Action
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('退出程序')
        exitAction.triggered.connect(self.close)

        # 底部状态栏
        self.statusBar().showMessage('状态栏看我')

        # 顶部菜单栏
        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('File')
        fileMenu.addAction(exitAction)

        # 次顶部的工具栏
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 500, 500)
        self.setWindowTitle('QMainWindow综合使用')
        self.show()
        pass

def main4():
    app = QApplication(sys.argv)
    example = Example4()
    sys.exit(app.exec_())
    pass

if __name__ == '__main__':
    main4()

效果

要点提示:setStatusTip设置的东西会在底部的状态栏显示。

<think>我们参考上述引用内容,来回答用户的问题:如何在PyQt5QMainWindow中添加菜单栏状态栏工具栏。 根据引用,我们知道: 1. 菜单栏使用QMenuBar类,通常位于主窗口顶部。 2. 工具栏使用QToolBar类,可以拖动或停靠。 3. 状态栏使用QStatusBar类,位于主窗口底部。 步骤: 1. 菜单栏(QMenuBar): - 通过`menuBar()`方法获取主窗口的菜单栏(如果没有则创建一个)。 - 然后使用`addMenu`方法添加菜单(如“文件”菜单),再在菜单中添加动作(QAction)。 2. 工具栏(QToolBar): - 使用`addToolBar`方法创建工具栏- 然后使用`addAction`方法将动作添加到工具栏。 3. 状态栏(QStatusBar): - 使用`statusBar()`方法获取主窗口的状态栏(如果没有则创建一个)。 - 使用`showMessage`方法显示临时消息,或添加永久部件。 注意:在Mac OS上,菜单栏可能显示在屏幕顶部,如果想使用应用程序内的菜单栏,可以设置`setNativeMenuBar(False)`。 下面是一个示例代码,演示如何添加菜单栏工具栏状态栏:</think>### PyQt5 QMainWindow 添加菜单栏状态栏工具栏PyQt5 中,`QMainWindow` 提供了标准应用程序框架的组件支持。以下是添加三要素的完整方法: #### 1. 添加菜单栏 (QMenuBar) ```python # 获取主窗口菜单栏(不存在则自动创建) menubar = self.menuBar() # 创建顶级菜单 file_menu = menubar.addMenu('文件(&F)') # &F 表示Alt+F快捷键 # 创建菜单动作 exit_action = QAction(QIcon('exit.png'), '退出(&X)', self) exit_action.setShortcut('Ctrl+Q') # 设置快捷键 exit_action.setStatusTip('退出程序') # 状态栏提示 exit_action.triggered.connect(qApp.quit) # 绑定事件 # 添加动作到菜单 file_menu.addAction(exit_action) # 创建子菜单(可选) import_menu = QMenu('导入', self) import_action = QAction('从CSV', self) import_menu.addAction(import_action) file_menu.addMenu(import_menu) # 添加到父菜单 ``` [^1][^2][^5] #### 2. 添加工具栏 (QToolBar) ```python # 创建工具栏 toolbar = self.addToolBar('主工具栏') # 添加工具动作(可复用菜单栏的action) new_action = QAction(QIcon('new.png'), '新建', self) toolbar.addAction(new_action) # 添加分隔符 toolbar.addSeparator() # 添加自定义控件(如按钮) save_btn = QPushButton(QIcon('save.png'), '保存') save_btn.clicked.connect(self.save_file) toolbar.addWidget(save_btn) # 设置工具栏特性 toolbar.setMovable(True) # 允许拖动 toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) # 图标+文字 ``` [^3][^4] #### 3. 添加状态栏 (QStatusBar) ```python # 获取状态栏(不存在则自动创建) statusbar = self.statusBar() # 显示临时消息(5秒后消失) statusbar.showMessage('准备就绪', 5000) # 添加永久部件(右侧显示) self.file_size_label = QLabel('0 KB') statusbar.addPermanentWidget(self.file_size_label) # 添加进度条(动态更新) self.progress_bar = QProgressBar() statusbar.addWidget(self.progress_bar, 1) # 拉伸系数为1 ``` [^1][^3] #### 完整代码框架 ```python import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import Qt class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # 添加菜单栏 menubar = self.menuBar() file_menu = menubar.addMenu('文件(&F)') # ... 添加菜单动作 # 添加工具栏 toolbar = self.addToolBar('工具') # ... 添加工具动作 # 添加状态栏 statusbar = self.statusBar() statusbar.showMessage('程序已启动') # 窗口设置 self.setGeometry(300, 300, 800, 600) self.setWindowTitle('PyQt5主窗口示例') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = MainWindow() sys.exit(app.exec_()) ``` **关键要点**: 1. 菜单栏通过 `menuBar()` 获取,使用 `addMenu()` 创建层级菜单 2. 工具栏通过 `addToolBar()` 创建,支持添加动作自定义控件 3. 状态栏通过 `statusBar()` 获取,支持临时消息永久部件 4. 所有组件共享 `QAction` 实现功能复用 5. Mac系统需 `menubar.setNativeMenuBar(False)` 显示程序内菜单栏[^2]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值