我想遍历 QML 网格的子项并使用 Javascript 销毁它们中的每一个。
Grid {
id: contentGrid
spacing: 10
ImageItem { imageSource: "file:/foo.jpeg" } // destroy this
ImageItem { imageSource: "file:/bar.jpeg" } // destroy this as well
}
我试过做这样的事情,但目前还行不通。
for(var i = 0; contentGrid.children.length() < i; i++) {
contentGrid.childAt(i).destroy();
}
最佳答案
你在上面的尝试中遇到了很多问题......首先,你需要向后迭代,因为你会在前进时向下移动子项的内容(即,如果你删除#1,数字#2 将成为 child #1,然后您将删除 #2,这将是旧 child #3)。
其次,您需要以不同方式访问子项。 childAt() 函数用于将 child 定位在屏幕上特定的 x,y 位置,而不是列表中的位置。
试试这个:
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()
}
}
}
}
关于javascript - 删除 QML 网格的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851164/