我需要帮助在 PyQt5 中制作菜单栏 [英] I need help making a menu bar in PyQt5
问题描述
几天以来,我一直在尝试在我的程序中实现菜单栏,但似乎无法运行.我希望有人查看我的代码并给我一个模板来制作菜单栏.
I have been trying to implement a menu bar in my program for a few days now and i cant seem to get one running. I would like someone to look at my code and give me a template to follow to making a menu bar.
class MainWindow(QMainWindow):
def __init__(self, databaseFilePath, userFilePath):
super(MainWindow,self).__init__()
self.moviesFilePath = moviesFilePath
self.currentUserFilePath = currentUserFilePath
self.createWindow()
def changeFilePath(self):
self.currentUserFilePath = functions_classes.changeFP()
functions_classes.storeFP(self.currentUserFilePath, 1)
def createWindow(self):
self.setWindowTitle('Movies')
#Menu Bar
fileMenuBar = QMenuBar().addMenu('File')
当从菜单栏文件调用名为更改用户数据库位置"的菜单选项时,我希望调用方法 changeFilePath.我已经读到行动是实现这一目标的关键,但是当我尝试实施它们时,它们都没有奏效.
The method changeFilePath is what I would like to be called when a menu option called 'Change user database location' is called from the menu bar File. I have read that actions are the key to this but when every i have tried to implement them they haven't worked.
推荐答案
QMainWindow
类已经有一个 菜单栏.
所以你只需要添加菜单到它,然后添加一个动作到那个菜单,比如这个:
So you just need to add a menu to it, and then add an action to that menu, like this:
def createUI(self):
...
menu = self.menuBar().addMenu('File')
action = menu.addAction('Change File Path')
action.triggered.connect(self.changeFilePath)
编辑:
这是一个基于您的示例类的完整工作示例:
Here's a full, working example based on your example class:
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, databaseFilePath, userFilePath):
super(MainWindow,self).__init__()
self.databaseFilePath = databaseFilePath
self.userFilePath = userFilePath
self.createUI()
def changeFilePath(self):
print('changeFilePath')
# self.userFilePath = functions_classes.changeFilePath()
# functions_classes.storeFilePath(self.userFilePath, 1)
def createUI(self):
self.setWindowTitle('Equipment Manager 0.3')
menu = self.menuBar().addMenu('File')
action = menu.addAction('Change File Path')
action.triggered.connect(self.changeFilePath)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow('some/path', 'some/other/path')
window.show()
window.setGeometry(500, 300, 300, 300)
sys.exit(app.exec_())
这篇关于我需要帮助在 PyQt5 中制作菜单栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!