Python PyQt5 如何在QWidget中显示完整的QMenuBar

2024-05-18 08:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用QMenuBar时得到了一个奇怪的结果,我以前在QMenuBar中使用过这个精确的代码,它工作得非常好。但它显示的不超过1QMenu

这是我的密码:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import sys
from functools import partial

class MainMenu(QWidget):
    def __init__(self, parent = None):
        super(MainMenu, self).__init__(parent)
        # background = QWidget(self)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(5, 35, 5, 5)
        self.menu()
        self.setWindowTitle('Control Panel')
        self.setWindowIcon(self.style().standardIcon(getattr(QStyle, 'SP_DialogNoButton')))
        self.grid = QGridLayout()
        lay.addLayout(self.grid)
        self.setLayout(lay)
        self.setMinimumSize(400, 320)


    def menu(self):
        menubar = QMenuBar(self)

        viewMenu = menubar.addMenu('View')
        viewStatAct = QAction('Dark mode', self, checkable=True)
        viewStatAct.setStatusTip('enable/disable Dark mode')
        viewMenu.addAction(viewStatAct)

        settingsMenu = menubar.addMenu('Configuration')
        email = QAction('Set Email', self)
        settingsMenu.addAction(email)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainMenu()
    main.show()
    sys.exit(app.exec_())

结果:

enter image description here

我知道我在使用QWidget而我应该使用QMainWindow但是有解决方法吗???你知道吗

(我为照片的糟糕质量提前道歉,没有好的方法给一个QMenuBar拍照)


Tags: fromimportselfinitmaindefsyspyqt5
1条回答
网友
1楼 · 发布于 2024-05-18 08:19:21

问题是,对于QWidget,您没有使用QMainWindow所具有的“private”布局,它会自动调整特定子窗口小部件(包括菜单栏、状态栏、停靠窗口小部件、工具栏,显然还有“centralWidget”)的大小。
记住QMainWindow有自己的布局(不能也不应该更改),因为它需要特定的自定义布局来布局前面提到的小部件。如果要为主窗口设置布局,则需要将其应用于^{}。你知道吗

仔细阅读Main Window Framework的行为);如文档报告所示:

Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.

为了在使用基本QWidget时解决这个问题,您必须相应地手动调整子widget的大小。在您的情况下,只要有对菜单栏的引用,就只需调整菜单栏的大小:

    def menu(self):
        self.menubar = QMenuBar(self)
        # any other function has to be run against the *self.menubar* object
        viewMenu = self.menubar.addMenu('View')
        # etcetera...

    def resizeEvent(self, event):
        # calling the base class resizeEvent function is not usually
        # required, but it is for certain widgets (especially item views 
        # or scroll areas), so just call it anyway, just to be sure, as
        # it's a good habit to do that for most widget classes
        super(MainMenu, self).resizeEvent(event)
        # now that we have a direct reference to the menubar widget, we are
        # also able to resize it, allowing all actions to be shown (as long
        # as they are within the provided size
        self.menubar.resize(self.width(), self.menubar.height())

注意:您也可以通过self.findChild(QtWidgets.QMenuBar)或使用objectName来“查找”菜单栏,但是使用实例属性通常是一个更简单更好的解决方案。你知道吗

相关问题 更多 >