问题描述
我想遍历 QML Grid 的子节点并使用 Javascript 销毁每个子节点.
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,编号#2 将成为孩子#1,然后您将去删除#2,这将是旧的孩子#3).
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).
其次,您需要以不同的方式访问孩子.childAt() 函数用于在屏幕上的特定 x,y 处定位孩子,而不是列表中的位置.
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.
试试这个:
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()
}
}
}
}
这篇关于删除 QML Grid 的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!