如何从列 QML 元素中删除动态创建的项目

How to Remove a dynamically created item from Column QML Element

[编辑]:我想删除一些在 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.
}

//How to remove perticular element from above column ?

使用下面提到的代码[参考::

col.children[index_to_destroy].destroy()

[编辑] 在列中动态添加和删除元素的示例代码:

Item
{
    ListModel {
        id: elementModel
        ListElement { elementColor: "red"; elementWidth: 50; elementHeight: 50}
        ListElement { elementColor: "green"; elementWidth: 20; elementHeight: 50}
        ListElement { elementColor: "blue"; elementWidth: 50; elementHeight: 20}
    }

    Column {
        id:col
        spacing: 2
        Repeater {
            model: elementModel
            Rectangle { color: elementColor; width: elementWidth; height: elementHeight }
        }
    }

    Button
    {
        id: deleteButton; x: 200; y: 200; height: 50; width: 50; text: "Delete"
        onClicked:
        {
            //How to remove perticular element from above column ?
            elementModel.remove(index)
        }
    }

    Button
    {
        id: addButton; x: 400; y: 200; height: 50; width: 50; text: "Add"
        onClicked:
        {
            // Code to add controls dynamically to column.
            elementModel.insert(index, { "elementColor": "red", "elementWidth": 50, "elementHeight": 50})
        }

    }
}