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

时间:2017-07-29 08:40:07

标签: qt qml qtquick2 qt-quick qtquickcontrols2

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

1 个答案:

答案 0 :(得分:1)

  

//如何从上面的列中删除perticular元素?

使用下面提到的代码[参考:https://stackoverflow.com/a/8852535/3459185]

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})
        }

    }
}