Qt Reference Documentation

QML Basic Type: variant

A variant is a generic property type. A variant type property can hold any of the basic type values:

 Item {
     property variant aNumber : 100
     property variant aString : "Hello world!"
     property variant aList : [ 1, 2, "buckle my shoe" ]
 }

The variant type can also hold a copy of a JavaScript object. For example, the animal property below defines a JavaScript object defined with JSON notation. The object's properties and values can be examined using the standard JavaScript syntax, as shown in the Component.onCompleted handler.

 Item {
     property variant animal : { 'type': 'bird', 'species': 'galah', 'age': 7 }

     Component.onCompleted: {
         for (var attribute in animal)
             console.log(attribute, "=", animal[attribute])
     }
 }

It must be noted that the animal property holds a copy of the defined object, and not the object itself. (This is true even if the property refers to an object defined in some JavaScript file; the property will hold a copy of the object, and not the actual object.) The property essentially holds a copy of the contents within the object. This has several implications:

  • Changes to any of the property's values (for example, the animal.type value above) only modify the copy of the object, not the object itself. You can, however, modify a copy of the object and then reassign the property to the modified value.
  • Because the property only holds a copy of the object, bindings to any of the property's individual values are not updated until the whole property is reassigned to a new value. For example:
        Item {
            property variant animal : { 'type': 'bird', 'species': 'galah', 'age': 7 }
    
            Text { text: "Animal species: " + animal.species }
    
            Component.onCompleted: {
                animal.species = 'kookaburra'    // this has no effect on the displayed text
    
                var newObj = animal
                newObj.species = 'kookaburra'
                animal = newObj  // this will update the displayed text
            }
        }
  • Since the object values are copied, it does not hold any reference to the original object, and extra data such as the object's JavaScript prototype chain is lost in the process.

See also QML Basic Types.

X

Thank you for giving your feedback.

Make sure it is related to this specific page. For more general bugs and requests, please use the Qt Bug Tracker.