如何使用具有多个 python 文件的 QML 来构建 PyQt5 项目?

How to architect a PyQt5 project using QML with multiple python files?

我刚刚开始使用 PyQt5 和 QML,目前有一个包含一些简单代码的 main.py 文件:

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load('QML/MainWindow.qml')
    sys.exit(app.exec_())

在我的 MainWindow.QML 中,我有一个 ApplicationWindow,带有一个工具栏和一个 StackView,它当前根据按钮点击等推送和弹出不同的 QML 文件。

我很好奇是否有适当的方法为每个 QML 文件使用 Python 文件,有点像 WPF,其中有 Settings.xaml 和 Settings.xaml.cs。我想要 Settings.qml 和一个 Settings.py 文件,其中包含为该页面划分的模型和逻辑,而不是有一个庞大的 main.py 文件。

我最终通过执行以下操作解决了这个问题:

Main.py:

def settings_clicked():
    stackView.push(Settings(engine, stackView).load())

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)

    engine = QQmlEngine()

    component = QQmlComponent(engine)
    component.loadUrl(QUrl('QML/MainWindow.qml'))

    mainWindow = component.create()

    stackView = mainWindow.findChild(QObject, "stackView")

    home = Home(engine, stackView)
    home.load()

    sys.exit(app.exec_())

Home.py(StackView 中的第一个初始页面)

class Home:

    def __init__(self, engine, stackview):
        self.engine = engine
        self.stackview = stackview

    def load(self):
        self.component = QQmlComponent(self.engine)
        self.component.loadUrl(QUrl('QML/Home.qml'))

        self.home = self.component.create()

        self.settings_button = self.home.findChild(QObject, "settingsButton")
        self.settings_button.clicked.connect(self.settings_clicked)

        self.stackview.push(self.home)

    def settings_clicked(self):
        self.settings = Settings(self.engine, self.stackview)
        self.settings.load()

Settings.py:

class Settings:
    def __init__(self, engine, stackview):
        self.engine = engine
        self.stackview = stackview

    def load(self):
        self.component = QQmlComponent(self.engine)
        self.component.loadUrl(QUrl('QML/Settings/Settings.qml'))

        self.settings = self.component.create()

        # Attach to signals, etc.

        self.stackview.push(self.settings)

这将使我能够将业务逻辑组织到不同的 Python 页面中,并为 GUI 提供单独的 QML 文件。