use*_*153 7 python macos pyqt menubar pyqt5
我一直在使用PyQt5开发GUI,并希望包含一个菜单栏.但是,当我编写此功能时,我的菜单不会出现.弄清楚我对如何在PyQt5中实现菜单栏的理解是关闭的,我在网上找了一个预先存在的例子.通过一些调整,我开发了以下测试用例:
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction, qApp
class Example(QMainWindow):
def __init__(self):
super().__init__()
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
exitAction.triggered.connect(qApp.quit)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&Testmenu')
fileMenu.addAction(exitAction)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
然而,当我运行它时,Testmenu无处可寻.
我还尝试在QTCreator中创建菜单栏(以及我的GUI布局的其余部分),然后使用pyuic5将.ui文件转换为可导入的.py文件.我认为这会消除我的一些编程错误,但菜单栏仍然不会显示.有什么想法吗?
编辑:
我在Jupyter笔记本4.1版本中使用Python 3.5(Anaconda 4.1)运行此代码.我也在使用运行os 10.1l,PyQt 5.7和Qt 5.7.0版本的Macbook.
我已经意识到,如果我单击应用程序窗口然后单击返回窗口,菜单栏将变为响应 - 有效地不聚焦并聚焦应用程序.有了这些信息,我意识到我不是第一个注意到这个问题的人(见https://github.com/robotology/yarp/issues/457).不幸的是,我仍然不确定如何解决这个问题.
Nij*_*lai 11
菜单栏在 PyQt5 中不可见
bar = self.menuBar()
bar.setNativeMenuBar(False)
file = bar.addMenu("File")
file.addAction("New")
Run Code Online (Sandbox Code Playgroud)
NativeMenuBar 属性指定菜单栏是否应在支持它的平台上用作本机菜单栏。如果此属性为 true,则菜单栏在本机菜单栏中使用并且不在其父级的窗口中,如果为 false,则菜单栏保留在窗口中。
示例程序
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
class Menu(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
exitAct = QAction(QIcon('exit.png'), ' &Quit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)
bar = self.menuBar()
file = bar.addMenu("Edit")
file.addAction("New")
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Simple menu')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Menu()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
这不是Qt和PyQt5错误。
我认为您的代码是zetcode pyqt5菜单栏教程。我在Mac OS上遇到了完全相同的问题。
第一个解决方案是一个把戏。使用' &Exit'代替'&Exit'。'&Exit'像这样在开头插入一个空格:
...
# exitAction = QAction(QIcon('exit.png'), '&Exit', self) # Not shown
exitAction = QAction(QIcon('exit.png'), ' &Exit', self)
...
Run Code Online (Sandbox Code Playgroud)
macOS的系统级菜单栏保留诸如"Exit","Quit"等的关键字。出于相同的原因,yurisnm的示例代码仅显示菜单项,但"Quit"Mac OS 除外。实际上,“ Quit”具有TextHeuristicRole,因此将覆盖“应用程序”菜单中的“ Quit”行为。当您在“ Python”菜单中单击“退出python”时,它不会退出,而仅显示“退出触发”。
如果必须在其他菜单中使用该名称(例如,“文件”,“编辑”),则需要像上面那样更改动作名称或使用QAction::setMenuRole(...)以下方式:
...
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
print(exitAction.menuRole()) # It prints "1". QAction::TextHeuristicRole
exitAction.setMenuRole(QAction.NoRole)
...
Run Code Online (Sandbox Code Playgroud)
请阅读以下内容,它将对您有帮助。