javascript - 删除 QML 网格的子项

标签 javascript qt grid qml children

我想遍历 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/

相关文章:

performance - 确定由线段接触的规则二维网格中的所有单元格的最快方法是什么

javascript - 如何使用正则表达式在字符串中找到没有相邻重复项的第一个字符?

c++ - 菜单栏上添加了qt按钮

javascript - 为什么 Node fs.watchFile 使测试无法完成?

c++ - 当你在 Qt 中使用 setLayout 时,Layouts 会成为你的 child 吗

c++ - Qt 5.3 : Accessing/returning/calling checkboxes that are created dynamically(? )

html - CSS 页脚格式

extjs - 在组合框选择上过滤商店

javascript - 使用多个复杂对象对数组项进行分组

javascript - 路由不重定向到静态文件