[solved] How to check for null contextProperty in QML?



  • Sometimes I need to setContextProperty("juice", nullptr). And I don't want JavaScript in QML to output any error. So I have tried the following in QML to check for null, but there is still an error output:
    @
    ToolButton {
    text: {
    if ( !juice ) { // trying to check for null, but there is still an error: ReferenceError: juice is not defined
    return "N/A";
    }
    return juice.name;
    }
    }
    @


  • Moderators

    @
    if (juice == undefined)
    @


  • Moderators

    To add to sierdzio
    @
    if(typeof(juice)=="undefined")
    @



  • Thanks guys! This is working, no error at all:
    @
    if ( typeof(juice) == "undefined" || !juice )
    @

    This is not working though, still got ReferenceError: juice is not defined:
    @
    if (juice == undefined || !juice)
    @

    Here's what I found:

    Before any setContextProperty("juice", ...) is called, typeof(juice) will return “undefined”.

    After setContextProperty("juice", nullptr) is called, typeof(juice) returns “object”, but juice equals to null.

    After setContextProperty("juice", apple) is called, typeof(juice) returns "object", and juice equals to apple, of course.


  • Moderators

    Interesting find. Thanks for sharing :)



  • Ah well, after some pondering on the findings, I resorted to the following way:

    Always set context before loading QML, even if it's just a setContextProperty("juice", nullptr). This is just like we always initialize class fields before usage.

    Then the simplest check can be used in QML:

    @
    if ( !juice ) {
    @


Log in to reply
 

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