How to pass "this" from a QML element to a JS function

Like the this in C ++, Id must either have a QML element to pass itself into a JS function, or set a property for another element for itself. Is it possible?

For instance:

 Rectangle{ id:theParent property var theElement SomeElement{ id:theChild MouseArea { anchors.fill:parent onClicked: { someJsFunction(*whatGoesHere*) parent.theElement=*whatGoesHere* } } 

Or, consider the following:

 Rectangle{ id:theParent property var theElement SomeElement{ id:theChild } 

Then in SomeElement.qml:

 Rectangle{ MouseArea { anchors.fill:parent onClicked: { someJsFunction(*whatGoesHere*) parent.theElement=*whatGoesHere* } } } 

In this case *whatGoesHere* will be the instance of SomeElement from which they are called.

Is this possible in QML? I would have thought that the id property makes sense, but according to the docs, you cannot request the value of the id field, and in any case, id will not be available if my SomeElement was described in a separate file and whatGoesHere handler appeared above in this separate file , not in a specific instance.

+6
source share
3 answers

I have two additional suggestions:

First, for one use, pass an identifier, as basically a pointer to an element:

 MouseArea { id: myClicker; onClicked: { callFunc (myClicker); } } 

Then, if you need several elements to share this behavior, this means that you are using MVC so that the identifier works exactly the same:

 Repeater { model: 100; delegate: MouseArea { id: myClicker; onClicked: { callFunc (myClicker); } } } 

This is the classic part.

But in order to do even better, if you create your own components, keep in mind to create the property "self" helper, which correctly does the work of 'this':

 MouseArea { // component root definition id: base; property var self : base; // bind self on the I } 

Then use it as follows:

 Repeater { model: 100; delegate: MyComponent { onClicked: { callFunc (self); } } } 

Use it as often as you want!

+10
source

An instance of your SomeElement is its id property value, i.e. theChild . You can use it like this . To my knowledge, no other built-in method exists. But you can try adding your own hierarchy of QML elements with a property that will return this .

Another way is to get the children from some parent and use them. Thus, you get children, find the child you need and use this particular instance

0
source

If you define your element in a separate file, you can simply assign an id and use it. It will be valid only in the context of this instance:

SomeElement.qml

 Rectangle{ id: thisElement MouseArea { anchors.fill: parent onClicked: { someJsFunction(thisElement); parent.theElement = thisElement; } } } 
0
source

Source: https://habr.com/ru/post/957404/


All Articles