17

How do you check if a property is undefined in qml?

This is what I am trying to do:

Button {
    id: myButton
    text: if (text === "undefined"){"default text"}
}
muru
  • 207,228
Anon
  • 12,339

4 Answers4

14

Try: text: text ? text : "default text"

"undefined" is just a string representation of a reference not referencing anything, just like None, or NULL in other languages.

=== is strict comparison operator, you might want to read this thread: https://stackoverflow.com/questions/523643/difference-between-and-in-javascript

Kissiel
  • 266
8
import QtQuick 2.3
import QtQuick.Controls 1.2

Button {
    id: myButton
    text: text ? text : "default text"
}

This answer throws a warning for me.

QML Button: Binding loop detected for property "text"

Changing text to modelText instead throws an error.

ReferenceError: modelText is not defined

This stops the Javascript execution for me; i.e. the next line isn't called.

Via Javascript

The same happens when setting it via Javascript, but is quite verbose.

import QtQuick 2.3
import QtQuick.Controls 1.2

Button {
    id: myButton
    text: "default text"

    Component.onCompleted: {
        if (modelText !== "undefined") {
            myButton.text = modelText;
        }
    }
}

Using typeof

The typeof operator mutes the error and works as expected.

import QtQuick 2.3
import QtQuick.Controls 1.2

Button {
    id: myButton
    text: "default text"

    Component.onCompleted: {
        if (typeof modelText !== "undefined") {
            myButton.text = modelText;
        }
    }
}
4

To compare with undefined you write text === undefined. This will evaluate to false if text is null.

If you want check if value is present (i.e., check for both undefined and null), use it as condition in if statement or ternary operator. If you need to store result of comparison as a boolean value, use var textPresent = !!text (though double ! might appear confusing to one reading the code).

tonytony
  • 141
1

Since no one has mentioned it, since Qt 5.15, you can also use the nullish-coalescing operator ?? operator to catch both undefined and null:

Button {
    id: myButton
    text: text ?? "default text"
}

If you want to be very explicit, QML allows us to bind to multiline expressions like so:

Button {
  id: myButton
  text: {
    if (text == null) {
      return "default text"
    }
    return text
  }
}

Note: The use of == null also works for undefined.

smac89
  • 1,085