Solved How can event handler in one component access object in another component?
-
Within a single qml file, how can an event handler invoked by one component access an object defined in another component? E.g. in this pseudocode, the onPressed mouse event handler within MouseArea wants to access an object a slider object contained within another Rectangle:
Rectangle { MouseArea { onPressed: // Mouse was pressed - reset slider scale mySlider.to = 20 // ReferenceError: mySlider is not defined } } } Rectangle { Slider { id: mySlider } }
But the code in the MouseArea onPressed event handler cannot see the mySlider object. I've read the Scope and Naming Resolution document but it isn't clear to me exactly how I do this.
Thanks
-
You can simplify it like this:
property alias sliderValue: mySlider.to Rectangle { MouseArea { onPressed: // Mouse was pressed - reset slider scale sliderValue.to = 20 // Referring to the property works } } } Rectangle { Slider { id: mySlider } }
-
So they are both in the same file? That should work. The only exception is if your mouse are is within a delegate - then you have to relay the signal through an intermediate property in your view component.
-
@sierdzio - thanks! Yes, the QML that assigns the id and the code that references the id is in a single file. I've never encountered the concept of a "delegate" - I've read this link, and I do not think my qml contains a delegate. My "hack" is to define a property which I assign to the slider id when the slider is created, and the MouseArea onPressed signal handler refers to that property:
property var theSlider: -1 Rectangle { MouseArea { onPressed: // Mouse was pressed - reset slider scale // mySlider.to = 20 // ReferenceError: mySlider is not defined theSlider.to = 20 // Referring to the property works } } } Rectangle { Slider { id: mySlider Component.onCompleted: { // Slider created - assign its id to property theSlider = mySlider; } } }
So I've got a workaround, but I don't know why it's needed!
-
You can simplify it like this:
property alias sliderValue: mySlider.to Rectangle { MouseArea { onPressed: // Mouse was pressed - reset slider scale sliderValue.to = 20 // Referring to the property works } } } Rectangle { Slider { id: mySlider } }