How to Remove a dynamically created item from Column QML Element

依然范特西╮ 提交于 2020-01-05 03:34:10

问题


[EDIT]: I want to remove some controls which are created in Column QML type dynamically and also how to access the children of a layout? .Following is the code which is not dynamic and is just for reference:

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:


//How to remove perticular element from above column ?

Use the below mentioned code [Reference: https://stackoverflow.com/a/8852535/3459185]:

col.children[index_to_destroy].destroy()

[EDIT] Sample code to add and delete elements dynamically in a column:

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

    }
}


来源:https://stackoverflow.com/questions/45387244/how-to-remove-a-dynamically-created-item-from-column-qml-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!