如何在 qml 的 ListModel 中找到特定的 ListElement? [英] How do I find a particular ListElement inside a ListModel in qml?

查看:15
本文介绍了如何在 qml 的 ListModel 中找到特定的 ListElement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt QML 有一个 ListModel 可以用于表示列表数据.它提供了许多向列表添加元素的方法,但我能找到的唯一检索元素的方法是 get() 方法,它需要一个索引.

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.

我想检查我的 ListModel 是否包含特定元素?有没有办法使用键和值接收 ListElement 对象?

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?

例如考虑这个列表:

ListModel {
    id: fruitModel

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

是否有诸如fruitModel.get({name: "Banana"}) 之类的方法可以找到名称为Banana"的元素并返回它们?

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

推荐答案

您将不得不迭代并检查列表元素.

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
}

您可以像这样使用它来查找名称为Banana"的项目:

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.

这篇关于如何在 qml 的 ListModel 中找到特定的 ListElement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆