QMainWindow常用(一)

设置中心窗口、窗口标题

  • setCentralWidget() 用来设置中心窗口;
  • setWindowTitle() 用来设置窗口标题;
    代码如下:
import sys

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        label = QLabel("Hello, World!")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.setCentralWidget(label)
        self.setWindowTitle("Hello MainWindow")


if __name__ == "__main__":
    app = QApplication()
    w = MainWindow()
    w.show()
    sys.exit(app.exec())

运行效果如图:


运行效果图

添加菜单

  • 调用QMainWindow.menuBar() 获取菜单栏
  • 添加菜单
    • 使用QMenu创建菜单;
    • 调用QMenuBar.addMenu() 为菜单栏添加菜单;
    • 也可以调用QMenu.addMenu() 为菜单添加子菜单;
  • 添加动作
    • 使用QAction创建动作;
    • 调用QMenu.addAction() 为菜单添加动作;
    • 调用QMenu.addSeprator() 为菜单添加分隔线;
      示例如下:
import sys

from PySide6.QtGui import QAction
from PySide6.QtWidgets import QApplication, QMainWindow, QMenu


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # 获取菜单栏
        menu_bar = self.menuBar()

        # 创建菜单
        menu_file = QMenu("&File")
        menu_help = QMenu("&Help")
        menu_recent = QMenu("&Recent")

        # 将菜单加入菜单栏
        menu_bar.addMenu(menu_file)
        menu_bar.addMenu(menu_help)

        # 创建动作
        self.act_file_new = QAction("&New")
        self.act_file_open = QAction("&Open")
        self.act_file_exit = QAction("&E&xit")
        self.act_help_help = QAction("&Help")

        # 动作加入菜单
        menu_file.addAction(self.act_file_new)
        menu_file.addAction(self.act_file_open)
        menu_file.addSeparator()  # 添加分隔线
        menu_file.addMenu(menu_recent)
        menu_file.addSeparator()
        menu_file.addAction(self.act_file_exit)
        menu_help.addAction(self.act_help_help)


if __name__ == "__main__":
    app = QApplication()
    w = MainWindow()
    w.show()
    sys.exit(app.exec())

运行效果如图:


菜单操作
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容