Why QQmlAppicationEngine crashes on exit if QApplication is not specifically referenced as parent?

161 Views Asked by At

I have a simple qml app, following the QmlBook tutorial. The Qml code is as such:

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
    }
}

I'm running it with the QQmlApplicationEngine using PyQt5. The python code to execute the application is as such:

def run_qml():
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine(parent=app)
    engine.load('main.qml')
    sys.exit(app.exec_())


if __name__ == '__main__':
    run_qml()

Every reference I have seen, the QmlApplicationEngine has always been declared as engine = QmlApplicationEngine(), however, when I run the code like this, it works, but then crashes when the application is exited with error QPixmap: Must construct a QGuiApplication before a QPixmap. This is fixed when I use engine = QmlApplicationEngine(parent=app) instead.

My question here is why this happens, as I would like to avoid making code decisions without properly understanding what I am doing.

0

There are 0 best solutions below