How to pass "this" from a QML element to a JS Function
-
I'd like to either have a QML element to pass itself into a JS function, or have it set a property on another element to itself. Is this possible?
For example:
@
Rectangle{
id:theParentproperty var theElement
SomeElement{
id:theChild
MouseArea {
anchors.fill:parent
onClicked: {
someJsFunction(whatGoesHere)
parent.theElement=whatGoesHere
}
}
@In this case, the whatGoesHere would be the instance of SomeElement where these are being set.
Is this possible in QML?
-
Just pass the QML Component ID (theParent or theChild).
-
yes but if you define SomeElement in a separate file and want to also define this functionality in that file, then you will not have access to a specific instance's id value.
Is there a generic keyword available instead? I was hoping for a property on Component but couldn't find anything apparently suitable.
Also suppose you are generating SomeElement dynamically.
-
Sure, that is how QML works: stuff from different QML files is not visible. All you can do is to make sure the var is passed to the root item of the file: then it will be visible as a property to other files that include that component.
As for dynamic generation: no worries, the instantiation methods return the component object, so you can use it straight away. When you instantiate in Loader, on the other hand, you need to use the "item" property.
-
The problem is that you are suggesting I pass the actual value of the id, such as theChild, but at the place in the code where I may wish to do this, i.e. in a separate QML file that defines only what SomeElement is, but has no knowledge of any particular instance of SomeElement, then I do not have an id value to use. I consolidated the code in my question which perhaps doesn't make the question clear.
Consider this:
@Rectangle{
id:theParentproperty var theElement
SomeElement{
id:theChild
}@Then, in SomElement.qml:
@
Rectangle{
MouseArea {
anchors.fill:parent
onClicked: {
someJsFunction(whatGoesHere)
parent.theElement=whatGoesHere
}
}
}@ -
OK, I did indeed misunderstand you. While what I've stated above is still true (and when you pass an ID to JavaScript, you are passing a pointer, so it can be used elsewhere), you are right that in your example it will not work: because you are not instantiating the component in the first file.
There are at least 3 ways of going around it:
- make a signal chain that will pass your pointer along the parent-child hierarchy (this is rather tedious and error prone)
- store the pointer as a root context property/ object (requires interfacing with C++, but is otherwise very convenient)
- create a QML Singleton (this is a new baby, I think it's available in Qt 5.1 or 5.2)