Global Object, Scope and javascript
-
main.qml
@
import Qt 4.7import "myscript.js" as MyScript
Rectangle {
id:mainMyScript.myFuction(); // This will execute fine, scope is fine SecondQML {
}
}
@myscript.js
@
function myFuction() {
print('inside my function');
}
@SecondQML.qml
@
Rectangle {MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
MyScript.myFunction(); // Will not execute
}
}
}
@I also tried main.MyScript.myFunction() it is out of scope. I need to be able to reference the same script instance bound in main.qml and not a newly initiated script from inside secondQML.qml
I can access main from here because of hierarchy but I am not sure why I cannot get to the MyScript property.
-
I don't believe it to be a parenting issue, as I have tried was you have suggested and made sure it was the proper parent. I think it has to do with the way the property MyScript is declared as an import. It might need to be referenced in a different manner or maybe it is not possible what I wish to do.
-
Hi,
Imports are document specific (we should try to make this clearer in the docs!), which is why the above is not working. A couple things you could try:
- Add a "wrapper" in main.qml; this wrapper should be accessible to children
@function myFunction() {
MyScript.myFuction();
}@ - Use the "library pragma":http://doc.qt.nokia.com/4.7/qdeclarativejavascript.html#stateless-javascript-libraries to import a shared copy of the script to both files.
Regards,
Michael - Add a "wrapper" in main.qml; this wrapper should be accessible to children
-
[quote author="oseeker" date="1289825785"]If import is document specific, how can I use the same global variant in two different qml files, they don't have any relationship.[/quote]
In most cases there will be a shared "root" QML file (the root of the QML tree for your application), which is accessible throughout the application (if the root component has id "root", its properties will be available to all ancestors as root.propertyName).
For a shared variable in a JS file, the "library pragma" solution mentioned above should allow access to the same value from different QML files (both QML files will need to import the JS file).