gpt4 book ai didi

javascript - 从 QML ListView 委托(delegate)调用 JavaScript 对象方法

转载 作者:行者123 更新时间:2023-12-01 11:16:19 24 4
gpt4 key购买 nike

我有一个带有 JavaScript 对象列表的 ListView 作为模型。委托(delegate)需要响应单击,我想存储附加到模型项的单击处理程序(action 属性):

ListView {
id: idListView
model: [
{
name: "Item 1",
icon: "icon1.svg",
action: function() {
//do stuff
}
},
/* other items */
]
delegate: MyDelegate {
name: modelData.name
icon: modelData.icon

MouseArea {
anchors.fill: parent
onClicked {
modelData.action()
}
}
}
}

但是当我点击一个项目时,我得到

TypeError: Property 'action' of object [object Object] is not a function



将函数附加到对象并调用它的正确方法是什么?

最佳答案

您应该将函数定义为 QML 属性。 Object不允许这样做,因此您可以使用 ListModel反而:

import QtQuick 2.11
import QtQuick.Window 2.11

Window {
id: root
visible: true
width:480
height: 640
title: qsTr("Hello World")

ListView {
anchors.fill: parent
spacing: 2
model: ListModel {
ListElement {
name: "Item 1"
property var func: function(){ console.log("Item 1 clicked"); }
}
ListElement {
name: "Item 2"
property var func: function(){ console.log("Item 2 clicked"); }
}
}

delegate: Rectangle {
height: 30
color: "#EFEFEF"
border { width: 1; color: "#CCC" }
width: parent.width
Text {
text: name
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
if(typeof func === "function")
func();
else
console.error("Click handler not defined");
}
}
}
}
}

另一个但有点被欺骗的解决方案:
import QtQuick 2.11
import QtQuick.Window 2.11

Window {
id: root
visible: true
width:480
height: 640
title: qsTr("Hello World")

ListView {
anchors.fill: parent
spacing: 2
property list<QtObject> arr: [
QtObject {
property string name: "Item 1"
property var func: function(){ console.log("Item 1 clicked"); }
},
QtObject {
property string name: "Item 2"
property var func: function(){ console.log("Item 2 clicked"); }
}
]
model: arr

delegate: Rectangle {
height: 30
color: "#EFEFEF"
border { width: 1; color: "#CCC" }
width: parent.width
Text {
text: modelData.name ? modelData.name : "Undefined item"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
if(typeof modelData.func === "function")
modelData.func();
else
console.error("Click handler not defined");
}
}
}
}
}

关于javascript - 从 QML ListView 委托(delegate)调用 JavaScript 对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50622945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com