Delete children of QML Grid

≡放荡痞女 提交于 2019-12-23 07:57:51

问题


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

回答1:


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



回答2:


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




回答3:


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




回答4:


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 = [];


来源:https://stackoverflow.com/questions/8851164/delete-children-of-qml-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!