Problem dynamically adding items in a ListModel



  • 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


  • Qt Champions 2017

    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.



  • @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



  • 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


  • Qt Champions 2017

    @Tom_H Starting from 2.11 you can assign the functions.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.