Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy/delete a QML component dynamically?

Tags:

qt

qml

I'm trying to dynamically create and then destroy a component based on user interaction with a checkbox in QML. Check box on, create component. Check box off, destroy component. Creating the component works, but destroying it doesn't. The component is still there.

The documentation in QT docs here mention that the destroy method should work after creating a component. Any ideas what I could be doing wrong here? Code given below.

import QtQuick 2.7
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.1

Rectangle {
    property var deficiencyType
    width: 600
    height: 800
    color:"white"
    CheckBox {
        id:checkbox
        text: "Check deficiency on/off"
        onClicked: {
            if (checked) {
                deficiencyType = Qt.createComponent("Form.qml")
                deficiencyType.createObject(columnRef)
            } else {
                deficiencyType.destroy()
                console.log(deficiencyType)
            }
        }
    }
    ColumnLayout {
        id:columnRef
        Layout.fillHeight: true
        Layout.fillWidth: true
        anchors {
            top: checkbox.bottom
            topMargin: 10
        }
    }
}
like image 775
cesium133 Avatar asked May 24 '26 10:05

cesium133


1 Answers

As @Alaenix said, a Loader may work for you instead. But to directly answer your question, the problem with your destroy() is that you're destroying the component, not the object that you created. So changing this code:

                    deficiencyType = Qt.createComponent("Form.qml")
                    deficiencyType.createObject(columnRef)

to this:

                    var component = Qt.createComponent("Form.qml")
                    deficiencyType = component.createObject(columnRef)

should resolve your problem.

like image 106
JarMan Avatar answered May 26 '26 07:05

JarMan