Delete children of QML Grid

alex picture alex · Jan 13, 2012 · Viewed 9.8k times · Source

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

Answer

Wes Hardaker picture Wes Hardaker · Jan 13, 2012

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