1

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

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.

4

2 回答 2

2

The QMainWindow class already has a menu-bar.

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)

EDIT:

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_())
于 2014-01-24T18:20:31.580 回答
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)

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

于 2014-01-24T15:04:14.497 回答