PyQt4 中 QMenuBar 的错误
An error with QMenuBar in PyQt4
我试过放一个 MenuBar 但它没有出现,我不知道我做错了什么。
from PyQt4 import QtGui
import sys
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setWindowTitle("IDE")
self.initUI
def initUI(self):
grid = QtGui.QGridLayout(self)
menuBar = QtGui.QMenuBar(self)
self.fileMenu = menuBar.addMenu("File")
grid.addWidget(menuBar, 0, 0)
self.setLayout(grid)
结果:
您需要在主菜单上设置菜单栏 window
self.setMenuBar(menuBar)
在很多情况下,您不需要手动创建菜单栏,您只需在主 window 上调用 .menuBar()
,它将 return 当前菜单栏或创建一个,如果它不存在。如果您的 .ui
文件可能包含菜单栏和菜单栏项,则这是首选方式。
menubar = self.menuBar()
此外,您不能将 QMenuBars
添加到布局 - from the docs:
There is no need to lay out a menu bar. It automatically sets its own geometry to the top of the parent widget and changes it appropriately whenever the parent is resized.
我试过放一个 MenuBar 但它没有出现,我不知道我做错了什么。
from PyQt4 import QtGui
import sys
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setWindowTitle("IDE")
self.initUI
def initUI(self):
grid = QtGui.QGridLayout(self)
menuBar = QtGui.QMenuBar(self)
self.fileMenu = menuBar.addMenu("File")
grid.addWidget(menuBar, 0, 0)
self.setLayout(grid)
结果:
您需要在主菜单上设置菜单栏 window
self.setMenuBar(menuBar)
在很多情况下,您不需要手动创建菜单栏,您只需在主 window 上调用 .menuBar()
,它将 return 当前菜单栏或创建一个,如果它不存在。如果您的 .ui
文件可能包含菜单栏和菜单栏项,则这是首选方式。
menubar = self.menuBar()
此外,您不能将 QMenuBars
添加到布局 - from the docs:
There is no need to lay out a menu bar. It automatically sets its own geometry to the top of the parent widget and changes it appropriately whenever the parent is resized.