pyside6(2):QMainWindow

1. Container components

The container component is used to host all visible UI components. The container component is a window that pops up during runtime, usually one of the QWindow , QWidget or QDialog  classes. For the difference between the three, see: Difference between QWidget, QMainWindow and QDialog_Nothing-Anything-CSDN Blog_Difference between qwidget and qdialog

If it is a top-level dialog box, it is generally created based on QDialog . If it is a main form, it is based on QMainWindow . If it is not sure, or it may be a top-level form, or it may be embedded in other forms, it is created based on QWidget .

2.QMainWindow

The main window of desktop software is generally composed of title bar, menu bar, toolbar, work area and status bar .

../../_images/mainwindowlayout.png

The workspace is composed of various anchor controls, such as Pycharm 's main window:

You can see that Pycharm 's main window workspace has three anchor controls by default, namely the file browser, debug window and code editor. QMainWindow provides the components needed to build the classic main window and the corresponding mouse events, which is used to simplify the construction of the main window of the application. The common settings of QMainWindow are as follows. For more information, see: QMainWindow — Qt for Python

3. Title bar settings

class MyWidget(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        # 设置标题
        self.setWindowTitle("QMainWindow示例")
        # 设置图标
        self.setWindowIcon(QPixmap(":/icon/ic_start"))

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())

hint

For QPixmap(":/icon/ic_start") in the code , see pyside6(1): Qt resource system and qrc file usage_anbuqi's blog-CSDN blog

4. Menu bar (QMenuBar) settings

4.1 Basic menu bar settings

QMainWindow adds a menu bar by default , which can be obtained through self.menuBar() . Add a menu item to the menu bar

fileMenu = self.menuBar().addMenu(QPixmap(":/icon/ic_start"),"文件")

When an icon object is passed in as a parameter, only the menu item icon is displayed by default, and the menu item name is not displayed:

class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        # 菜单栏设置
        self.setupMenuBar()
    
     def setupMenuBar(self):
        # 添加文件菜单项
        fileMenu = self.menuBar().addMenu(QPixmap(":/icon/ic_start"),"文件")
        # 文件菜单项下的动作列表
        newAct = QAction(QPixmap(":/icon/ic_start"), "新建", self)
        fileMenu.addAction(newAct)

        saveAct = QAction(QPixmap(":/icon/ic_start"), "保存", self)
        fileMenu.addAction(saveAct)

        exitAct = QAction(QPixmap(":/icon/ic_start"), "退出", self)
        fileMenu.addAction(exitAct)
        
        # 自定义快捷键
        exitAct.setShortcut('Ctrl+Q')
        # 状态栏提示
        exitAct.setStatusTip('Exit application')
        # 利用信号槽机制,将退出动作和窗口的关闭函数联系起来
        exitAct.triggered.connect(self.close)

if __name__ == "__main__":
    ......

Effect

 Notice

When creating a QAction , the window object self must be passed in , otherwise the QAction will not be displayed.

 4.2 Customize the menu bar

 A custom menu bar can be implemented through setMenuWidget of QMainWindow :

class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupTitleBar()

        self.setupCustomMenuBar()
       
    def setupCustomMenuBar(self):
        menuBar = QWidget()
        layout = QGridLayout()
        fileBtn = QPushButton("文件")
        layout.addWidget(fileBtn, 0, 0)
        editBtn = QPushButton("编辑")
        layout.addWidget(editBtn, 0, 1)
        helpBtn = QPushButton("帮助")
        layout.addWidget(helpBtn, 0, 2)
        menuBar.setLayout(layout)
        self.setMenuWidget(menuBar)


if __name__ == "__main__":
    ......

 In this way, a personalized menu bar can be customized, such as the menu bar of Youdao Dictionary:

5. Status bar settings (Q StatusBar )

The status bar is used to display current interface status messages or some prompts. The status bar can display the following three messages:

  • Temporary messages : Used to explain tooltip text or menu entries.
  • Normal messages : Occupies part of the status bar and may be covered by temporary messages. For example, page and line numbers displayed in a text editor.
  • Persistent Messages : Used to display important messages, such as syntax errors in the code editor.

QMaindow creates a QStatusBar by default, which can be obtained through self.statusBar() .

5.1 Display temporary messages

Will not disappear automatically until overwritten:

self.statusBar().showMessage("临时消息")

Timing disappears:

self.statusBar().showMessage("临时消息定时消失", 3000)

Notice

Temporary messages overlap each other , calling  showMessage continuously will only display the last set temporary message. For example:

        # 显示临时消息
        self.statusBar().showMessage("临时消息")
        # 显示临时消息,定时消失
        self.statusBar().showMessage("临时消息定时消失", 3000)

Only the message " Temporary message disappears periodically " will be displayed.

5.2 Display normal messages

Normal messages need to be added by calling the addWidget method of statusBar :

normalMessage = QLabel("正常消息")
# 组件名称
normalMessage.setObjectName('normalMessage')
self.statusBar().addWidget(normalMessage)
btn = QPushButton("消息按钮")
# 组件名称
btn.setObjectName('btn')
self.statusBar().addWidget(btn)

 Use removeWidget to remove normal messages: 

self.statusBar().removeWidget(self.statusBar().findChild(QLabel, 'normalMessage'))
self.statusBar().removeWidget(self.statusBar().findChild(QPushButton, 'normalBtn'))

5.3 Displaying permanent messages

permanentMessage = QLabel("永久消息")
# 组件名称
permanentMessage.setObjectName('permanentMessage')
self.statusBar().addPermanentWidget(permanentMessage)

permanentBtn = QPushButton("永久消息按钮")
# 组件名称
permanentBtn.setObjectName('permanentBtn')
self.statusBar().addPermanentWidget(permanentBtn)

  Persistent messages are also removed using removeWidget .

(4)demo

import sys

from PySide6 import QtWidgets
from PySide6.QtGui import QPixmap, QAction
from PySide6.QtWidgets import QVBoxLayout, QMainWindow, QWidget, QGridLayout, QPushButton, QLabel

import res


class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        centerWidget = QWidget()
        mainLayout = QGridLayout()

        showTemMessageBtn = QPushButton("显示一般临时消息")
        showTemMessageBtn.clicked.connect(self.showTempMessage)
        mainLayout.addWidget(showTemMessageBtn, 0, 0)

        showTemMessageBtn2 = QPushButton("显示定时消失临时消息")
        showTemMessageBtn2.clicked.connect(self.showTimingTemMessage)
        mainLayout.addWidget(showTemMessageBtn2, 0, 1)

        showNormalMessageBtn = QPushButton("显示正常消息")
        showNormalMessageBtn.clicked.connect(self.showNormalMessage)
        mainLayout.addWidget(showNormalMessageBtn, 0, 2)

        shoPermanentBtn = QPushButton("显示永久消息")
        shoPermanentBtn.clicked.connect(self.showPermanentMessage)
        mainLayout.addWidget(shoPermanentBtn, 0, 3)

        clearNormalMessage = QPushButton("移除正常消息")
        clearNormalMessage.clicked.connect(self.removeNormalMessage)
        mainLayout.addWidget(clearNormalMessage, 1, 0)

        clearPermanentMessage = QPushButton("移除永久消息")
        clearPermanentMessage.clicked.connect(self.removePermanentMessage)
        mainLayout.addWidget(clearPermanentMessage, 1, 1)

        centerWidget.setLayout(mainLayout)
        self.setCentralWidget(centerWidget)

    def removeNormalMessage(self):
        self.statusBar().removeWidget(self.statusBar().findChild(QLabel, 'normalMessage'))
        self.statusBar().removeWidget(self.statusBar().findChild(QPushButton, 'normalBtn'))

    def removePermanentMessage(self):
        self.statusBar().removeWidget(self.statusBar().findChild(QLabel, 'permanentMessage'))
        self.statusBar().removeWidget(self.statusBar().findChild(QPushButton, 'permanentBtn'))

    def showTempMessage(self):
        self.statusBar().showMessage("临时消息")

    def showTimingTemMessage(self):
        self.statusBar().showMessage("临时消息定时消失", 1000)

    def showNormalMessage(self):
        normalMessage = QLabel("正常消息")
        # 组件名称
        normalMessage.setObjectName('normalMessage')
        self.statusBar().addWidget(normalMessage)
        btn = QPushButton("正常消息按钮")
        # 组件名称
        btn.setObjectName('normalBtn')
        self.statusBar().addWidget(btn)

    def showPermanentMessage(self):
        permanentMessage = QLabel("永久消息")
        # 组件名称
        permanentMessage.setObjectName('permanentMessage')
        self.statusBar().addPermanentWidget(permanentMessage)

        permanentBtn = QPushButton("永久消息按钮")
        # 组件名称
        permanentBtn.setObjectName('permanentBtn')
        self.statusBar().addPermanentWidget(permanentBtn)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())

6. Drag and drop dockable components (QDockWidget)

The dockWidget can be docked in the surrounding area around the central control of the main window:

 The optional value of the docking position is defined by the DockWidgetArea class. There are four docking positions: up, down, left, and right. Multiple values ​​can be selected at one time, for example:

import sys

from PySide6 import QtWidgets
from PySide6.QtGui import QPixmap, QAction, Qt
from PySide6.QtWidgets import QMainWindow, QWidget, QGridLayout, QPushButton, QLabel, QDockWidget
import sys

from PySide6 import QtWidgets
from PySide6.QtGui import QPixmap, QAction, Qt
from PySide6.QtWidgets import QMainWindow, QWidget, QGridLayout, QPushButton, QLabel, QDockWidget


class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        # 往主窗口添加停靠窗口
        dockWidget = QDockWidget("Dock Widget", self)
        # 设置可停靠位置为左和右
        dockWidget.setAllowedAreas(Qt.LeftDockWidgetArea |
                                   Qt.RightDockWidgetArea)
       
        self.addDockWidget(Qt.LeftDockWidgetArea, dockWidget)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())


class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        # 往主窗口添加停靠窗口
        dockWidget = QDockWidget("Dock Widget", self)
        # 设置可停靠位置为左和右
        dockWidget.setAllowedAreas(Qt.LeftDockWidgetArea |
                                   Qt.RightDockWidgetArea)
       
        self.addDockWidget(Qt.LeftDockWidgetArea, dockWidget)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())

 Effect:

Guess you like

Origin blog.csdn.net/anbuqi/article/details/120468791