我最終通過執行以下操作解決這個:
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文件。