Accessing the positions of delegates



  • Hi!

    I have a ListView displaying data of a ListModel and I use a delegate to display items of this model. For instance, suppose the delegate is used to render each item as a rectangle. More or less like this:

    @Component {
    id: myDelegate

    Rectangle {
        width: 40
        height: 40
    }
    

    }

    ListView {
    model: myModel
    delegate: myDelegate
    }
    @
    So, if my model has, say, 3 items, there will be 3 rectangles. Now I need to access, from outside the ListView, the position (x and y properties) of each of these 3 rectangles. How can I do this? Are these rectangles children of the ListView?

    Thanks!



  • You can access the currentItem, but a ListView is intended for the case where it is the sole manager of the positioning and instantiation of the delegates. So you cannot even be assured that all the rectangles will exist at any one time.

    If you want to have an effect communicating with non-currentItems, then you can have the delegate itself propagate some of the information. For example, by setting a global variable.

    If your use case is more complex, and involves all the items being instantiated at the same time, consider using a Repeater instead of a ListView. The Repeater element creates all of the items at once, and places them inside the same item as the Repeater is, so that you can access them more easily.



  • I need the 'x,y' properties just to bind the position of other objects to it:

    @

    otherObject.x: anItem.x + 42
    otherObject.y: anItem.y - 42

    @

    I'm not planning to change them.

    Anyway, I thing I will try your Repeater solution. It seems to do the trick.

    Nevertheless, I'm a bit curious: how could a make the delegate store the position of the items in (for example) global variables? Could you please give me an example?

    Tkanks!



  • Just another question: the Repeater itself is counted as its parent's children? Or is it included in the resources property?



  • [quote]Just another question: the Repeater itself is counted as its parent's children? Or is it included in the resources property?[/quote]

    Repeater is a type of Item, and so is counted as a child of its parent. It works this way so that the Repeater can identify the spot where it should be inserting its items. For example, in the QML below it needs to insert its items between the Rectangle and Image.

    @Column {
    Rectangle {}
    Repeater {}
    Image {}
    }@

    [quote]Are these rectangles children of the ListView?[/quote]

    They become children of the ListView's contentItem. (but as aalpert said, are created and destroyed dynamically)



  • Hmm, I see.

    Thank you very much


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.