7

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

Herr von Wurst
  • 2,571
  • 5
  • 32
  • 53
VALOD9
  • 566
  • 2
  • 6
  • 22

2 Answers2

14

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.

Cinder Biscuits
  • 4,880
  • 31
  • 51
3

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;
                }
            }
        }
    }

    // ...
}
Simon Warta
  • 10,850
  • 5
  • 40
  • 78
  • 1
    I'm trying to implement treeview using the combination of `ListView`s in `ListView`. I want to have a possibility to hide and show lists of some roots. And also I need `Show/Hide all button`. – VALOD9 Mar 29 '15 at 13:32
  • I'd avoid doing that because it is not trivial to get nested `ListView`s to work properly. Confirm [Roll your own Qt Quick TreeView](https://www.qtdeveloperdays.com/north-america/roll-your-own-qt-quick-treeview) and the presentation at the end of the page. Or [this](http://www.codeproject.com/Articles/632795/QML-TreeModel-and-TreeView). If you feel confident to tackle this kind of task, go ahead and follow up with more specific questions. – Simon Warta Mar 29 '15 at 13:41
  • 2
    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. – BaCaRoZzo Mar 29 '15 at 13:56