2012-11-07 228 views
11

你能告诉我下面的代码是否有任何方法来改变imgx元素的属性。我必须改变使用JavaScript的imgx.x值。或者还有其他方法吗?我搜索qt文档,但没有帮助。谢谢。如何在QML中访问Repeater儿童的属性?

Row { 
    Repeater { 
     id:mmm 
     model : 10 
     Rectangle{ 
      clip: true 
      width: 54 
      height: 80 
      color:"transparent" 
      Image { 
       id:imgx 
       //x:-160 
       //x:-105 
       //x:-50 
       x:0 
       source: "images/tarama_lights.png" 
      } 
     } 
    } 
} 

回答

18

你必须将属性添加到R​​epeater(矩形你的情况)的直接孩子,并将其设置为内部子属性(图片你的情况)的目标。然后您可以使用mmm.itemAt(<index of the element>).<property> = value。代码:

Repeater { 
    id:mmm 
    model : 10 
    Rectangle{ 
    clip: true 
    width: 54 
    height: 80 
    color:"transparent" 
    property int imageX: 0 //adding property here 

    Image { 
     id:imgx 
     x: parent.imageX //setting property as the target 
     source: "images/tarama_lights.png" 
    } 
    } 
} 

然后,您可以更改属性是这样的:

onPropertyChange: { 
    mmm.itemAt(index).imageX = newValue //the index defines which rectangle you change 
} 
+1

谢谢。这非常有帮助。 –

+0

@JuliusG你会如何得到你点击的任何东西的索引? – MrPickles

+1

@MrPickles查看childAt(...)方法:http://doc.qt.io/qt-5/qml-qtquick-item.html#childAt-method – JuliusG

2

JuliusG的答案是正确的使用itemAt。但不需要将其设置为内部子项目的目标(您的案例中的图片)。 您可以有你的代码,因为它是和代替

onPropertyChange: { mmm.itemAt(index).imageX = newValue //the index defines which rectangle you change } 

使用本:

onPropertyChange: { mmm.itemAt(index).children[0].x = newValue //the index defines which rectangle you change } 

希望它能帮助。