我有一个简单的 qml 应用程序,遵循 QmlBook 教程。Qml 代码如下:
Window {
id: root
visible: true
width: Screen.width / 2
height: Screen.height / 2
title: "Happy Windmill"
onHeightChanged: console.log('new window height: ', height)
property int spins: 0
property int fpresses: 0
Image {
id: background
anchors.fill: parent
source: "assets/background.png"
MouseArea {
anchors.fill: parent
onClicked: {
wheel.rotation += 90
incrementSpinCounter()
}
}
Image {
id: pole
source: "assets/pole.png"
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
anchors.top: wheel.verticalCenter
}
Image {
id: wheel
source: "assets/pinwheel.png"
anchors.centerIn: parent
Behavior on rotation {
NumberAnimation {
duration: 250
}
}
}
}
function incrementSpinCounter(){
spins += 1
}
function incrementFCounter(){
fpresses += 1
}
}
我正在使用 PyQt5 与 QQmlApplicationEngine 一起运行它。执行应用程序的python代码如下:
def run_qml():
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine(parent=app)
engine.load('main.qml')
sys.exit(app.exec_())
if __name__ == '__main__':
run_qml()
我见过的每一个引用,QmlApplicationEngine
总是被声明为
engine = QmlApplicationEngine()
,但是,当我像这样运行代码时,它可以工作,但是当应用程序退出并出现错误时崩溃QPixmap: Must construct a QGuiApplication before a QPixmap
。当我改为使用时,这是固定的engine = QmlApplicationEngine(parent=app)
。
我的问题是为什么会发生这种情况,因为我想避免在没有正确理解我在做什么的情况下做出代码决策。