I want to loop through a QML Grid's children and destroy each of them using Javascript.
Grid {
id: contentGrid
spacing: 10
ImageItem { imageSource: "file:/foo.jpeg" } // destroy this
ImageItem { imageSource: "file:/bar.jpeg" } // destroy this as well
}
I tried to do something like this but it's not working so far.
for(var i = 0; contentGrid.children.length() < i; i++) {
contentGrid.childAt(i).destroy();
}
You have a number of problems in your attempt above... First, you'll need to iterate backwards because you'd be shifting the contents of the children down as you advance (ie, if you delete #1, number #2 would become child #1 and then you'd go to delete #2 which would be the old child #3).
Second, you need to access the children differently. The childAt() function is for locating a child at a particular x,y on the screen, not a position in a list.
Try this instead:
import QtQuick 1.0
Rectangle {
width: 400
height: 400
Grid {
id: contentGrid
spacing: 10
Text { text: "foo" } // destroy this
Text { text: "bar" } // destroy this as well
}
MouseArea {
anchors.fill: parent
onClicked: {
for(var i = contentGrid.children.length; i > 0 ; i--) {
console.log("destroying: " + i)
contentGrid.children[i-1].destroy()
}
}
}
}
or you can just say: grid.children = "";
I just want to copy & paste a fragment from documentation:
Note that you should never manually delete objects that were dynamically created by convenience QML object factories (such as Loader and Repeater). Also, you should avoid deleting objects that you did not dynamically create yourself.
Then, the answer is YOU SHOULDN'T do it! Try to create the object dynamically if you want to delete it later.
Documentation
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