Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Looping over a QVariantList Q_PROPERTY in QML



  • Hi,

    I had exposed a QVariantList (can be converted into a QStringList) as a Q_PROPERTY to my QML code. I was using it to populate a combo box (by setting it as the model). Now, this recently someone created a function in QML which I am required to call over every object in this particular list before setting it into the combo box.

    Basically, I need to call list2[listIndex] = func(list[listIndex]) over every element in the list and save the new values to a separate list to set as model.

    I tried writing a for loop to loop over the list, but I realized that I have no way to know it's length. listName.length returns 0. I also don't want to create a property when defining a list, so I am stuck with the inability to append the output of func to list2 as well.

    Any help would be appreciated,
    Thanks
    Ankit


  • Qt Champions 2018

    length is defined for a QVariantList, I tested with a context property and also via Q_PROPERTY.

    But you don't need it, you can just use Array.map():

    model: list1.map(n => n * 2)
    

    EDIT: And if your are doing that because you now have a list of objects instead of a list of strings, make sure to check the textRole property of ComboBox, it might help you.



  • @GrecKo Thanks for check on the length variable. Maybe I had some other bug originally when I tested, but that part's working.
    The Array.map() function on the other hand isn't. I wrote something similar to what you had defined

    contextName.listName.map(x => context2Name.obj.func(x))
    

    and the code gave me a syntax error on the "=>" symbol. I don't think that QVariantList is treated as a list type. I tried setting it to a list property to see it fail.

    Anyway, I am thinking of trying QQmlListProperty once.

    P.S. The QVariantList is a list of strings and I am using Qt v5.6.2


  • Qt Champions 2018

    x => context2Name.obj.func(x) is a shorthand for function (x) { return context2Name.obj.func(x); } but it is only available since Qt 5.12 with the support of EcmaScript 6 and later.

    In your case you can just do:

    contextName.listName.map(context2Name.obj.func)
    

    since map's parameter is a function that it applies on each element of your array.

    Don't use QQmlListProperty, it's for declaring a list property that is meant to be populated from QML.


Log in to reply