Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete children of QML Grid

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();
}
like image 658
alex Avatar asked Jan 13 '12 13:01

alex


3 Answers

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()
      }
    }
  }
}
like image 112
Wes Hardaker Avatar answered Nov 11 '22 04:11

Wes Hardaker


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

like image 3
mshefiti Avatar answered Nov 11 '22 04:11

mshefiti


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

like image 3
albertTaberner Avatar answered Nov 11 '22 05:11

albertTaberner