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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With