[solved] How to check for null contextProperty in QML?
-
wrote on 1 Aug 2014, 01:39 last edited by
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;
}
}
@ -
@
if (juice == undefined)
@ -
To add to sierdzio
@
if(typeof(juice)=="undefined")
@ -
wrote on 1 Aug 2014, 13:18 last edited by
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.
-
Interesting find. Thanks for sharing :)
-
wrote on 1 Aug 2014, 22:21 last edited by
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 ) {
@
4/6