是否有可能从内部(它们是嵌套的)到达外部 QML 中继器的索引?

2022-01-19 00:00:00 nested qtquick2 qml c++ repeater

我正在尝试在我的 QML 应用程序中动态构建相同类型项目的矩阵并使其保持动态,以便您可以随时更改 c++ 文件中的行数和列数.这一直运作良好,但现在,要单独访问它们,我想给它们动态名称.因此,我嵌套了两个中继器并尝试将 objectName 设置如下:

I am trying to dynamically build a matrix of the same type of items in my QML application and keep it dynamic, so that you can change the number of rows and columns in a c++ file anytime. This has been working well, but now, to access them individually, I want to give them dynamic names. Therefore I nested two repeaters and tried to set the objectName as in the following:

    Repeater{
        id: rows
        model: Matrix1.row //number of rows in Matrix1-Object

        Repeater{
            id: columns
            model: Matrix1.column //number of columns in Matrix1-Object

            RepeatedItem{
                objectName: (index) +"."+ (rows.index) //matrix elements are 
                supposed to be numbered x.y because of the nested repeaters, e.g. 
                0.0 for the first element
            }
        }
    }

不幸的是,我似乎无法访问外部索引.显示第一个值,第二个值由我的 GUI 的 TextArea 中的字符串 undefined 表示.如果我向外部中继器添加一个新属性并将其设置为与索引相同的值,它将被设置一次并为每个重复行保留第一个值 (0).

Unfortunately I seem to have no access to the outer index. The first value is shown, the second value is represented by the String undefined in the TextArea of my GUI. In case I add a new property to the outer Repeater and set it the same value as index, it will be set once and keep the first value (0) for each repeated row.

是否不可能以某种方式动态地达到这个外部索引值?或者有谁知道在 QML 中动态创建可单独访问的二维项目数组的更好方法?

Is it impossible to dynamically reach this outer index value somehow? Or does anyone know a better way to dynamically create two-dimensional arrays of items in QML which are individually accessable?

推荐答案

index 属性是上下文属性.你可以将它存储到一个普通的属性中,这样你就可以从另一个上下文中访问它:

The index property is a context property. You can store it to an ordinary property, so you can access it from another context:

Repeater {
    id: rows
    // ...
    Repeater {
        id: columns
        property int outerIndex: index
        // ...
        Text {
            text: index + "." + columns.outerIndex
        }
    }
}

相关文章