Foreach delegate in QML view

16,821

Solution 1

While Simon's answer is a best practice, to answer the actual question being asked you need to iterate over the children of ListView's contentItem like so:

ListView {
    id: list
    model: mymodel
    delegate: Text {
        objectName: "text"
        text: name + ": " + number
    }
}

for(var child in list.contentItem.children) {
    console.log(list.contentItem.children[child].objectName)
}

You can then filter using objectName or any other property of the delegate Item.

Solution 2

Are you sure you want to iterate over delegates? In most cases you want to iterate over the model because in case of a ListView there might be only a handful of delegates even if your model has 100 entries. This is because a delegate is re-filled when it moved out of the visible area.

You need a model that has a function like for example at() which returns the model element for a given position. Than you can do something like

ListView {
    // ...

    function find(convId)
    {
        // count is a property of ListView that returns the number of elements
        if (count > 0)
        {
            for (var i = 0; i < count; ++i)
            {
                // `model` is a property of ListView too
                // it must have an at() metghod (or similar)
                if (model.at(i)["id_"] === convId)
                {
                    return i;
                }
            }
        }
    }

    // ...
}
Share:
16,821
VALOD9
Author by

VALOD9

Updated on June 16, 2022

Comments

  • VALOD9
    VALOD9 almost 2 years

    Is it possible to iterate through the delegates of a ListView or GridView using foreach or a similar function?

  • VALOD9
    VALOD9 about 9 years
    I'm trying to implement treeview using the combination of ListViews in ListView. I want to have a possibility to hide and show lists of some roots. And also I need Show/Hide all button.
  • Simon Warta
    Simon Warta about 9 years
    I'd avoid doing that because it is not trivial to get nested ListViews to work properly. Confirm Roll your own Qt Quick TreeView and the presentation at the end of the page. Or this. If you feel confident to tackle this kind of task, go ahead and follow up with more specific questions.
  • BaCaRoZzo
    BaCaRoZzo about 9 years
    B.t.w. Treeview will be soon available with Qt 5.5 in a month or so. Alpha release is already available if you want to give it a try.