0

I am looking to access a function inside a repeater element in qml. Wether i try calling the function directly or connecting signals between rect1 and rect2, it cannot seem to work. What am i missing or is there any other way to do this ?

The code below is a simplified version of what i am working with.

Rectangle {
    signal save
    id : rect1
    onSave : {
        rect2.saveState()
    }
    Repeater {
        id: repeat1
        model: length
        delegate:
            Row {
            id: row1

            Rectangle {
                id: rect2

                function saveState()
                {
                    rect2.grabToImage(function(result) {result.saveToFile(filepath);});
                }
            }
        }
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Because you are using a Repeater, you can kinda look at it like there are an unknown amount of `rect2`, which one do you wish to use? – Amfasis Feb 16 '21 at 14:45
  • I see. Let's say i want to use the first one, how can i do that ? – Romain Ferrier Feb 16 '21 at 15:07
  • 1
    With the Repeater you get the property `count` and the method `itemAt(index)` https://doc.qt.io/qt-5/qml-qtquick-repeater.html#itemAt-method Be aware of the creation of the repeated Item and the access to it. `itemAt()` returns `null` if the `Repeater` hasn't finished creating the items. Use `Component.onCompleted` for that. – iam_peter Feb 16 '21 at 16:19

2 Answers2

0

Since you are using the function inside the repeater you will be having multiple copies of that function you can still use children of that rectangle to call that function. See the below code

 Rectangle {
    signal save
    id : rect1
    onSave : {
        rect1.children[1].saveState()
        rect1.children[2].saveState()
        rect1.children[3].saveState()
        rect1.children[4].saveState()
        rect1.children[5].saveState()
        rect1.children[6].saveState()
    }
    Repeater {
        id: repeat1
        model: 6
        delegate:
            Row {
            id: row1
            property var saveState: rect2.saveState
            Rectangle {
                id: rect2
                
                function saveState()
                {
                    console.log("index",index)
                    rect2.grabToImage(function(result) {result.saveToFile(filepath);});
                }
            }
        }
    }
}

Rectangle {
    anchors.fill: parent
    color: "#55550000"
    MouseArea{
        anchors.fill: parent
        onClicked: rect1.save()
    }
    
}
Bibin
  • 433
  • 5
  • 12
0

You can use method itemAt(index) of Repeater class to access specific Rectangle. For instance you want to call first Rectangle function.

Component.onCompleted : {
        repeat1.itemAt(0).saveState()
    }
smalik
  • 343
  • 4
  • 9