1

数日前からプログラムにメニュー バーを実装しようとしていますが、実行できないようです。誰かに私のコードを見て、メニュー バーを作成するためのテンプレートを提供してもらいたいです。

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 は、「ユーザー データベースの場所を変更する」というメニュー オプションがメニュー バー ファイルから呼び出されたときに呼び出されたいものです。アクションがこれの鍵であると読んだことがありますが、それらを実装しようとするたびに、それらは機能しませんでした。

4

2 に答える 2

2

クラスにはQMainWindowすでにmenu-barがあります。

したがって、次のように、メニューを追加して、そのメニューにアクションを追加するだけです。

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

おそらくいくつかのより良い解決策があります (しかし、なぜ Designer を使用しなかったのですか?) が、これは機能するはずです。

于 2014-01-24T15:04:14.497 に答える