Global Object, Scope and javascript



  • main.qml
    @
    import Qt 4.7

    import "myscript.js" as MyScript

    Rectangle {
    id:main

    MyScript.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.



  • try parent.MyScript.myFunction();



  • TypeError: Result of expression 'parent.MyScript' [undefined] is not an object.



  • try parent.parent.MyScript.myFunction(); because the first parent is the rectangle from SecondQML and the parent to that is main rectangle



  • 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:

    Regards,
    Michael



  • Hi
    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 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).


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.