How to pass JS function to a ListModel
-
Hi, i want to append objects to a ListModel.
In the delegate there is a MouseArea.onClicked handle.
This handle should call a function that I want to pass to the model.I tried to pass it to an object like this.
@
var obj = {"label":"OK","callback":function() {console.log('foobar')}};
bottonModel.append();
@I can call callback() from obj. That works fine.
But in the delegate i can't call callback() because "Property 'callback' of object [object Object] is not a function".
Qml doesn't pass the function as callable JS function. How can I pass a function to a dynamically created ListElement ? -
The ListElement documentation says:
Values must be simple constants; either strings (quoted and optionally within a call to QT_TR_NOOP), boolean values (true, false), numbers, or enumeration values (such as AlignText.AlignHCenter).If you can't find another way around it, the function can be passed as text, and transformed into a function within the delegate via eval().
-
Not the best solution, but it is a workaround:
@import QtQuick 2.2
import QtQuick.Window 2.1Window {
visible: true
width: 360
height: 360ListModel { property var functions: []; id: bottonModel } ListView { anchors.fill: parent model: bottonModel delegate: MouseArea { width: 50 height: 50 Rectangle { anchors.fill: parent color: "red" radius: 5 Text { anchors.fill: parent text: label horizontalAlignment: Text.AlignHCenter } } onClicked: { bottonModel.functions[index](); } } Component.onCompleted: { bottonModel.append({"label":"OK"}); bottonModel.functions.push(function() {console.log("foobar"); }); } }
}
@Of course you need to keep model index and function index in sync, which I left out.