QML:在ListView中调用的ListElement中定义函数

PH-*_*ero 1 listview function qml

在QML ListView中,我想在单击MouseArea时调用函数:

ListView{
    anchors.fill: parent
    orientation: ListView.Horizontal

    model: myModel

    delegate:
    Rectangle {
        anchors.fill: parent
        Text {
            anchors.centerin: parent
            text: label
        }
        MouseArea {
            width: 30
            height: parent.height
            onClicked: {
                doSomething()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该是一个溢出菜单.在ListModel(myModel)中,我希望能够说出调用doSomething()时会发生什么.我怎么做?也许是这样的?

ListModel {
    id: myModel

    ListElement {
        label: "New"
        doSomething: {
            canvas.clear()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道.我在网上搜索,但我找不到任何东西.
我正在使用ListView/Model,因为我想动态添加和删除菜单项.
感谢您的关注!=)

coy*_*508 5

qrc:///main.qml:49 ListElement:不能将脚本用于属性值

这就是你的代码所带来的.因此,您不能将模型元素的任何属性设置为脚本.

我通过将函数放在模型中而不是模型元素来逃避它:

ListView{
    anchors.fill: parent
    orientation: ListView.Horizontal

    model: myModel

    delegate:
    Rectangle {
        anchors.fill: parent
        color: "red"
        Text {
            anchors.centerIn: parent
            text: label
        }
        MouseArea {
            anchors.centerIn: parent
            width: 30
            height: parent.height
            onClicked: {
                myModel.actions[label]();
            }
        }
    }
}

ListModel {
    id: myModel

    property var actions : {
        "New": function(){ console.log("clicked!"); }
    }

    ListElement {
        label: "New"
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然基于文本的索引操作有点像meh,但您应该这样做,以便模型中的每个元素都具有唯一属性(如索引)并将其用作actions词典的键.

(在旁注中,你忘记了centerIn鼠标区域,我想知道为什么你使用宽度为30而不是只填充父级)