Context object being available to JS



  • Hi,

    I have added an object to my context and this is available from the QML as such:

    @
    _engine->rootContext()->setContextProperty( "Proxy", _proxy );
    @

    and this works great in QML:

    @
    property variant size: Proxy.getFunction1()
    @

    If I try to use it in a JS file that is included in my QML as such:

    @
    function function2() {
    Proxy.function2();
    }
    @

    I get the following error:

    qrc:/qml/js/uni.js:17: ReferenceError: Can't find variable: Proxy

    Can't I add an object reference which is accessible from JS?

    Thanks in advance, Andy

    [EDIT: code formatting, please wrap in @-tags, Volker]



  • Hi Andy,

    One solution to the problem is to assign your context object to a javascript object.

    For example if you have, in a qml file, something like :
    @
    import "AppLogic.js" as AppLogic
    Page {
    id: mainPage
    }
    @

    together with a js like this:
    @
    var contextObj = ""
    ///the rest of your JS file
    @

    You can connect the context obj to "contextObj" at startup in the qml..

    @
    import "AppLogic.js" as AppLogic
    Page {
    id: mainPage
    Component.onCompleted: {
    AppLogic.contextObj = Proxy; //given that Proxy is the obj u added to the context
    }
    }
    @

    That way, after startup your JS file you'll have a "bridge" to the context object.
    Works for me.. :D



  • Would that be easy to pass the context obj as a parameter

    @
    // inside javascript
    function doSomething(contextObj) {
    ...
    }
    @



  • Yep.. would be easier but depending on what you're doing it would be a bit uglier.. or not.. :D


Log in to reply
 

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