Search code examples
qtviewmodelqmlrepeater

Access modelData within delegate in QML


Is there a way to access modelData from View delegate (Repeater in particular).

I tried to use a separate property and tried to access it via model.modelData but neither of this worked.

Please see code snapshot below.

Thanks in advance.

Component
{
    id: comp_1
    Rectangle
    {
        color: "green"
        width: 200
        height: 200
    }
}

Component
{
    id: comp_2
    Rectangle
    {
        color: "red"
        width: 200
        height: 200

        Text
        {
            anchors.fill: parent
            text: modelData
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }
    }
}

function getDelegate(itemName)
{
    if(itemName === "comp1")
        return comp_1;
    else
        return comp_2;
}

Row
{
    Repeater
    {
        id: repeat
        model: ["comp1", "comp2"]
        Loader
        {
            sourceComponent: getDelegate(modelData)
        }
    }
}

Solution

  • You could add a property on the delegate element

    Component {
        id: comp_1
        Rectangle {
            property string valueFromModel
        }
    }
    

    and bind the modelData to it

    Loader {
        id: loader
        Binding {
            target: loader.item
            property: "valueFromModel"
            value: model.modelData
        }
    }