Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach delegate in QML view

Tags:

qt

qml

qtquick2

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

like image 426
VALOD9 Avatar asked Mar 29 '15 13:03

VALOD9


2 Answers

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.

like image 94
Cinder Biscuits Avatar answered Oct 16 '22 10:10

Cinder Biscuits


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

    // ...
}
like image 3
Simon Warta Avatar answered Oct 16 '22 11:10

Simon Warta