How to delete QML object

Viewed 4461

I am trying to delete QML object and recreate object like this:

Rectangle{
    property var obj

    signal videoStopped(variant complete)

    function recreate(url){
        if(!obj){
            console.log("createObject")
            obj = videoComponet.createObject(root)
            obj.stopped.connect(function(){
                videoStopped(obj.status == MediaPlayer.EndOfMedia)
            })
        }
        obj.source = url
        obj.play()
    }
    function stop(){
        obj.destroy() // obj.deleteLater()
    }
    Component{
        id: videoComponet
        Video {
            anchors.fill: parent
            visible: true
            autoPlay: true; autoLoad: true
        }
    }
}

C++ side call recreate to generate an object and call stop to delete it.

  1. recreate ⇒ console output createObject

  2. stop

  3. recreate ⇒ console no output

Both obj.destroy() and obj.deleteLater() not worked. How to forcedly delete the dynamically created object just like delete in C++.

2 Answers

A minor change to S.M.Mousavi's answer: I observed that setting sourceComponent to undefined does not work. I have to set it to null to unload the component. Another option is to set the source to empty string.

onClicked: {
    loader.sourceComponent = null; //causes destroying loaded component
}

OR

onClicked: {
    loader.source = ""; //causes destroying loaded component
}
Related