【问题标题】:Access modelData within delegate in QML在 QML 中的委托中访问 modelData
【发布时间】:2023-03-25 18:49:01
【问题描述】:

有没有办法从 View 委托(特别是Repeater)访问modelData

我尝试使用单独的属性并尝试通过model.modelData 访问它,但这都不起作用。

请看下面的代码快照。

提前致谢。

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

【问题讨论】:

  • 你看到this页面了吗?

标签: qt view model qml repeater


【解决方案1】:

您可以在委托元素上添加一个属性

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

并将modelData绑定到它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多