前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PySide6 GUI 编程(23):MenuBar 与 ToolBar搭配使用

PySide6 GUI 编程(23):MenuBar 与 ToolBar搭配使用

原创
作者头像
bowenerchen
发布2024-07-31 21:22:37
2370
发布2024-07-31 21:22:37
举报
文章被收录于专栏:编码视界

带有菜单的界面

示例代码

代码语言:python
代码运行次数:0
复制
from typing import List

from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QAction, QIcon
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QToolBar


class MyMenuBar(QMainWindow):
    def __init__(self, icon_paths: List[str], show_toolbar: bool = False):
        super().__init__()

        self.setWindowTitle('MenuBar Test')
        self.setIconSize(QSize(32, 32))

        self.label = QLabel('My Menu Bar Demo')
        self.label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)
        self.setCentralWidget(self.label)
        if show_toolbar:
            self.tool_bar = QToolBar('test tool bar', self)
            self.tool_bar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
            self.addToolBar(self.tool_bar)
        self.menu_bar = self.menuBar()
        # 在 macOS 上,菜单项通常只显示文本,不显示图标
        # 如果在其他平台(如 Windows 或 Linux)上运行相同的代码,你应该能看到菜单项旁边的图标
        # 如果需要在所有平台上都显示图标,可能需要使用自定义的菜单和工具栏,而不是使用系统的菜单栏
        # 因此 macOS 上,向 addMenu 函数里面传 QIcon 不会生效
        self.my_menu_1 = self.menu_bar.addMenu(QIcon(icon_paths[0]), 'MyMenu-1')
        self.my_menu_2 = self.menu_bar.addMenu(QIcon(icon_paths[1]), 'MyMenu-2')

        count = 0
        for icon_path in icon_paths:
            button_action = QAction(QIcon(icon_path), 'button-{}'.format(count), self)
            if show_toolbar:
                self.tool_bar.addAction(button_action)
                self.tool_bar.addSeparator()
            if count % 2 == 0:
                self.my_menu_1.addAction(button_action)
            else:
                self.my_menu_2.addAction(button_action)
            count += 1


if __name__ == '__main__':
    icons = [
        'xxxxxx/Mountain_king_by_seashxlls.png',
        'xxxxxx/os_ubuntu_icon.png',
        'xxxxxxs/ubuntu-plain-icon.svg',
        'xxxxxx/ubuntu-wallpaper-d.png',
        'xxxxxx/warty-final-ubuntu.png',
        'xxxxxx/Ubuntu_warrior_by_jt05.png',
        'xxxxxx/MacOS_Sonoma.icns',
    ]
    app = QApplication()
    # 是否渲染工具栏
    ins = MyMenuBar(icon_paths = icons, show_toolbar = True)
    ins.show()
    app.exec()

代码逻辑分析

工具栏与菜单栏主体逻辑
工具栏与菜单栏主体逻辑

菜单栏效果

不带有工具栏

菜单栏与主界面
菜单栏与主界面
菜单栏按钮
菜单栏按钮

带有工具栏

带有工具栏的主界面
带有工具栏的主界面
菜单栏与工具栏
菜单栏与工具栏

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 带有菜单的界面
    • 示例代码
      • 代码逻辑分析
      • 菜单栏效果
        • 不带有工具栏
          • 带有工具栏
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档