带有 ID 的 Qml 中继器

Joh*_*ith 5 qt qml

如果写了下面的代码:

Repeater { model: 10; 
delegate: Rectangle { width: 200; height:           
20; color: "white";}}
Run Code Online (Sandbox Code Playgroud)

我怎样才能给所有 10 个矩形一个不同的 id?

eyl*_*esc 8

您不能分配不同的 id,而且 id 有一个范围,其限制是委托,如果您想访问一个项目,您必须使用itemAt()传递索引的方法:

Repeater { 
    id: repeater
    model: 10; 
    delegate: Rectangle { 
        width: 200; 
        height: 20; 
        color: "white";
    }
}

// ...

var item = repeater.itemAt(2)
Run Code Online (Sandbox Code Playgroud)

  • @JohnSmith 你可以给文本一个像 `textInput` 这样的 id 并像 `repeater.itemAt(2).textInput` 一样访问它 (2认同)

Adr*_*vat 5

根据您想要做什么,您可以

A. 从​​索引访问该项目

您可以使用转发器的方法访问元素的索引itemAt,如 @eyllanesc 所示。请小心,因为委托可能尚未实例化。

    Repeater { 
        id: repeater
        model: 5

        Component.onCompleted: {
            if (repeater.count > 0) {
                var firstRect = repeater.itemAt(0)
                // do something
            }
        }

        Rectangle { /*...*/ }
   }
Run Code Online (Sandbox Code Playgroud)

B. 使用itemAdded信号

您可以连接到itemAdded的信号Repeater。每当添加项目(当然)时都会触发此信号,并将提供项目indexitem

    Repeater { 
        id: repeater
        model: 5

        property Item firstRect

        onItemAdded: {
            // `index` and `item` come from the signal
            if (index == 0) {
                firstRect = item
                // Or do something with item
            }
        }

        Rectangle { /*...*/ }
    }
Run Code Online (Sandbox Code Playgroud)

C. 委托将自己分配给一个属性

您可以让矩形将自己分配给在其父级之一中声明的属性。这通常不是首选,因为您的委托现在依赖于该命名属性,但它可能很有用。

    Repeater { 
        id: repeater
        model: 5

        // That property can be anywhere
        property Item firstRect

        Rectangle {
            id: rect
            width: 50; height: 50;
            Component.onCompleted: { 
                // Index is automatically populated by the Repeater
                if (index == 0)                
                    repeater.firstRect = rect
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

大多数时候,您希望避免代表对家长的任何依赖,因此首选解决方案 A 和 B。但这总是要看情况!