Problem dynamically adding items in a ListModel
-
wrote on 25 Oct 2018, 10:10 last edited by
Hello,
I have a list model with a number of elements:
items: ListModel { id: pagesModel ListElement { pageTitle: qsTr ("Settings") pageIcon: "qrc:/Resources/settings.svg" action: function() { stackView.push(Qt.resolvedUrl("/qml/Settings.qml")) } } ... }
I want to dynamically add elements to the model. So I am doing:
pagesModel.append({"pageTitle": qsTr ("Title"), "pageIcon": "qrc:/Resources/stuff.svg", "action": function() { stackView.push(Qt.resolvedUrl("/qml/Stuff.qml"), {"deviceId":linkId}) }, });
However, at execution time, I get the following error:
<Unknown File>: Can't assign to existing role 'action' of different type [VariantMap -> Function]Any idea what I might be doing wrong there?
Thanks,
Cyrille -
You can use the dynamicRoles:true. In the beginning don't have any elements. Dynamically add all of them. It should work. Not sure why this error though.
-
Hello,
I have a list model with a number of elements:
items: ListModel { id: pagesModel ListElement { pageTitle: qsTr ("Settings") pageIcon: "qrc:/Resources/settings.svg" action: function() { stackView.push(Qt.resolvedUrl("/qml/Settings.qml")) } } ... }
I want to dynamically add elements to the model. So I am doing:
pagesModel.append({"pageTitle": qsTr ("Title"), "pageIcon": "qrc:/Resources/stuff.svg", "action": function() { stackView.push(Qt.resolvedUrl("/qml/Stuff.qml"), {"deviceId":linkId}) }, });
However, at execution time, I get the following error:
<Unknown File>: Can't assign to existing role 'action' of different type [VariantMap -> Function]Any idea what I might be doing wrong there?
Thanks,
Cyrillewrote on 25 Oct 2018, 22:29 last edited by Tom_H@Cyrille-de-Brebisson
I don't think you can assign a function as a value. ListElement role values must be simple constants, i.e. strings, numbers, or booleans.Edit: Deleted wrong information as pointed out by @dheerendra
-
wrote on 26 Oct 2018, 06:32 last edited by
Hello,
One solution that I found was to setup the "action" AFTER the append. This seemed to work...
Why, I do not know. Another issue is that since append does not seem to return the position of insertion, what happends if another thread does an insert just after. my count-1 will refer to what at this point?pagesModel.append({"pageTitle": qsTr (ttle), "pageIcon": icon, "model": m2 }); pagesModel.setProperty(pagesModel.count-1, "action", function() { console.log("My Action"); stackView.push(Qt.resolvedUrl(url), {"deviceId":linkId}) }); // for some reason I can no do this in the object creation!
Cyrille
-
@Tom_H Starting from 2.11 you can assign the functions.
1/5