如何在循环中初始化 qml 属性列表? [英] How to initialize qml property list in a loop?

查看:61
本文介绍了如何在循环中初始化 qml 属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 qml list 属性:

I have the qml list property:

Item {
    property list<SomeItem> items: [
        SomeItem { num: 0 },
        SomeItem { num: 1 },
        SomeItem { num: 2 },
        ...
        SomeItem { num: 100 }
    ]

是否可以以更聪明的方式对其进行初始化?例如.以某种方式类似于下面的代码?

Is it possible to initialize it in more clever way? E.g. in some way like the code below?

Item {
    property list<SomeItem> items

    ...

    Component.onCompleted: {
        for(var i = 0; i < 100; i++)
            ??? // items.append( SomeItem {num: i})
    }
}

对不起,id,我实际上想更改用于初始化其他属性的自定义属性(num):

Sorry for the id, I actually want to change my custom property (num) which is used to initialize other properties:

SomeItem {
    property int num: 0

    key: getKey(num)
    name: getName(num)

    function getKey(num) {
        return ...
    }

    function getName(num) {
        return ...
    }
}

EDIT 2(根据 Mitchddriver 的回答):我想使用 Repeater,但是我必须初始化一些外部库提供的列表属性.

EDIT 2 (according to Mitch and ddriver answers): I would like to use Repeater, however I have to initialize the list property which is provided by some external library.

我一直在用 num 属性初始化 SomeItem,因为 key 属性必须是唯一的并且不能为空.但是,假设我可以通过在 onCompleted 方法中设置 num 来应对它:

I've been initializing SomeItem with num property because the key property must be unique and not null. However let's say I can cope with it by setting the num in onCompleted method:

Item {
    property list<SomeItem> items: [
        SomeItem { },
        SomeItem { },
        SomeItem { },
        ...
        SomeItem { }
    ]

    ...

    Component.onCompleted: {
        for(var i = 0; i < items.length; i++)
            items[i].num = i
    }
}

所以主要问题是我必须添加 SomeItem {}, 行 100 次.有没有什么聪明的方法可以动态创建这样的属性列表?

So the main problem is that I have to add the SomeItem {}, line 100 times. Is there any clever way to create such property list dynamically?

推荐答案

没有

list 的文档描述可以使用的方式:

The documentation for list describes the ways that it can be used:

列表值的访问方式与 JavaScript 数组类似:

A list value can be accessed in a similar way to a JavaScript array:

  • 使用 [] 方括号语法和逗号分隔值分配值
  • length 属性提供列表中的项目数
  • 使用 [index] 语法访问列表中的值

最好使用 Repeater:

Repeater {
    model: 100

    delegate: SomeItem {
        num: index
    }
}

这篇关于如何在循环中初始化 qml 属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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