Remove children from a QML grid

I want to scroll the children of a QML grid and destroy each of them with 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 is not working yet.

 for(var i = 0; contentGrid.children.length() < i; i++) { contentGrid.childAt(i).destroy(); } 
+8
javascript qt grid children qml
source share
4 answers

You have a number of problems in your attempt above ... First, you will need to iterate backwards because you will move the contents of the children down as you move (i.e. if you delete # 1, number # 2 will become a child # 1, and then you go to delete # 2, which will be the old child # 3).

Secondly, you need to access your children in different ways. The childAt () function is designed to search for a child on a specific x, y on the screen, and not in a list 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() } } } } 
+11
source share

I just want to copy and paste a fragment from the documentation:

Note that you should never manually delete objects that were dynamically created using convenient QML object objects (such as Loader and Repeater). In addition, you should avoid deleting objects that you did not dynamically create yourself .

Then the answer: YOU SHOULD NOT DO IT! Try creating the object dynamically if you want to delete it later.

Documentation

+4
source share

or you can just say: grid.children = "";

+3
source share

As a complement to Atron's answer, note that the documentation explicitly mentions that destroy statically created object is not manually permitted:

 Item { SelfDestroyingRect { // ... } } 

This will result in an error, since objects can only be dynamically if they were dynamically created.

Therefore, I agree with mshefiti that the correct solution (for elements that are not dynamically created):

 grid.children = []; 
0
source share

All Articles