Python PyQt5如何显示带有QWidget的完整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个回答
1
投票

问题是,对于QWidget,您没有使用QMainWindow的“ private”布局,该布局会自动调整特定子控件的大小(包括菜单栏,状态栏,停靠控件,工具栏,以及,“ centralWidget”)。请记住,QMainWindow具有其自己的布局(不能也不应更改),因为它需要特定的自定义布局来layout前述小部件。如果要为主窗口设置布局,则需要将其应用于centralWidget

仔细阅读centralWidget的行为);作为文档报告:

注意:不支持创建没有中央窗口小部件的主窗口。您必须有一个中央小部件,即使它只是一个占位符。

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

Main Window Framework

注意:您也可以通过 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)来“查找”菜单栏,但是通常使用instance属性是一个更简单,更好的解决方案。

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