Question

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();
}
Was it helpful?

Solution

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()
      }
    }
  }
}

OTHER TIPS

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

As an addition to Atron's answer, note that the documentation explicitly mentions that destroying a statically created object manually is not allowed:

Item {
    SelfDestroyingRect {
        // ...
    }
}

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

Therefore, I agree with mshefiti that the correct solution (for items that aren't dynamically created) is:

grid.children = [];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top