Search code examples
qtqmlqtquick2qt-quickqtquickcontrols2

How to Remove a dynamically created item from Column QML Element


[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.
}

Solution

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