[編輯]:我想刪除它在列QML 型動態創建以及如何訪問一個佈局的孩子一些控制? 。繼是代碼這不是動態的,僅供參考:如何從列QML元素中刪除動態創建的項目
import QtQuick 2.6
import QtQuick.controls 2.2
Item
{
Column {
id:col
spacing: 2
//Initially Adding controls.
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
}
Button
{
id:button
onClicked:
{
//How to remove a perticular element from above column which is created dynamically?
}
}
// [EDIT] - Code to add controls dynamically to column.
}
可能的複製[刪除QML Grid的子項](https://stackoverflow.com/questions/8851164/delete-children-of-qml-grid) – m7913d
我通常會建議採用數據驅動的方法('Repe ater「等),而不是手動構建和銷燬元素。 – peppe
@ m7913d你不應該依賴垃圾收集器。只有當你使用'component.createObject(null)'時,它纔會起作用,然後隨着時間的推移它會緩解地破壞你的對象,很可能在你想要它消失之前,因爲引用計數被破壞了。如果它運行很少,那麼應用程序一運行就會崩潰。如果你使用'component.createObject(someParent)',它根本無法工作。然後它是你的責任,用'instance.destroy()'銷燬它。由於上述原因,這是處理來自JS的動態實例化的唯一合理方式。 – derM