我需要帮助在PyQt5中创建一个菜单栏

时间:2014-01-24 13:56:58

标签: python pyqt pyqt5

我一直试图在我的程序中实现一个菜单栏几天,我似乎无法运行。我希望有人看一下我的代码并给我一个模板来制作一个菜单栏。

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')

当从菜单栏File调用名为“更改用户数据库位置”的菜单选项时,我想要调用方法changeFilePath。我已经知道行动是关键,但是当我试图实施它们时,它们都没有用。

2 个答案:

答案 0 :(得分:1)

QMainWindow课程已有menu-bar

所以你只需要add a menu,然后add an action到该菜单,就像这样:

    def createUI(self):
        ...
        menu = self.menuBar().addMenu('File')
        action = menu.addAction('Change File Path')
        action.triggered.connect(self.changeFilePath)

修改

以下是基于示例类的完整实用示例:

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_())

答案 1 :(得分:0)

添加带有可用项目的菜单栏的逻辑就是这样的

def createUI(self):
        self.setWindowTitle('Equipment Manager 0.3')
        #Menu Bar
        fileMenuBar = QMenuBar(self)
        menuFile = QMenu(fileMenuBar)
        actionChangePath = QAction(tr("Change Path"), self)
        fileMenuBar.addMenu(menuFile)
        menuFile.addAction(actionChangePath)

然后,您只需要将动作actionChangePath与信号triggered()连接,例如

connect(actionChangePath,SIGNAL("triggered()"), changeFilePath)

可能有一些更好的解决方案(但你为什么不使用Designer?),但这个应该是可行的