Python PyQt5如何显示完整的QMenuBar

问题描述 投票:0回答:1

我在使用QMenuBar时得到了这个奇怪的结果,我之前在QMenuBar中使用了这个确切的代码,并且效果很好。但显示的数量不超过1 QMenu

这是我的代码:

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的照片]

python pyqt pyqt5 qmenubar
1个回答
0
投票

问题是,对于QWidget,您没有使用QMainWindow的“ private”布局,该布局会自动调整特定子控件的大小(包括菜单栏,状态栏,停靠控件,工具栏,以及,“ centralWidget”)。

为了解决此问题,您必须相应地手动调整子窗口小部件的大小。就您而言,只要您对菜单栏有引用,就只需要调整其大小即可:

    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
        uper(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来“查找”菜单栏,但是使用instance属性通常是一个更简单,更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.