Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find a particular ListElement inside a ListModel in qml?

Tags:

qt

qml

Qt QML has a ListModel that can be used to represent list data. It provide a number of methods for adding elements to the list but the only method I can find for retrieving an element is the get() method that expect an index.

What is I want to check if my ListModel contains a particular element? Is there a way to recieve ListElement object(s) using a key and value?

For example connsider this list:

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        cost: 1.95
    }
}

Is there a method such as fruitModel.get({name: "Banana"}) that would find elements with the name "Banana" and return them?

like image 402
Aras Avatar asked Feb 01 '17 23:02

Aras


1 Answers

You will have to iterate and check the list elements.

It is a good idea to write a function if you are going to be performing different searches, where you can pass search criteria as a functor:

function find(model, criteria) {
  for(var i = 0; i < model.count; ++i) if (criteria(model.get(i))) return model.get(i)
  return null
}

Which you can use like this, to find an item with the name of "Banana":

find(fruitModel, function(item) { return item.name === "Banana" })

If multiple hits are possible, you should return an array of items instead of a single item.

like image 82
dtech Avatar answered Oct 16 '22 11:10

dtech