我想根据计数动态多次实例化“sample.qml”中的图像。我能够在运行时创建多个 qml 实例,如下所示,
Item {
id: container
width: 500; height: 100
z: 100
Component.onCompleted: {
var component = Qt.createComponent("sample.qml");
for (var i=0; i< model.count; i++) {
var object = component.createObject(container);
object.x = (object.width + 250) * i;
}
}
}
创造不是问题。 但我想在运行时将 x 属性分配给特定实例。如何实现这一点以及如何销毁特定实例。任何建议都会非常有帮助。谢谢。
我无法获取该组件的特定实例。 此外,在使用 destroy 时,它仅销毁最后创建的实例。
正如评论中提到的,中继器是一种更好的方法。它使您能够在创建特定实例后引用它们。
Item {
id: container
width: 500; height: 100
z: 100
Repeater {
id: repeater
// A model can be as simple as an integer
model: some_number
// The delegate is the object that you want repeated
delegate: SomeObject {
required property int index
x: (width + 250) * index
}
}
Component.onCompleted: {
// Update the 5th item
repeater.itemAt(4).color = "blue";
}
}