var QML Value Type

一般的なプロパティタイプ。詳細

詳細な説明

var 型は、任意のデータ型を参照できる汎用プロパティ型です。

これは通常のJavaScriptの変数に相当します。例えば、varプロパティは数値、文字列、オブジェクト、配列、関数を格納することができます:

Item {
    property var aNumber: 100
    property var aBool: false
    property var aString: "Hello world!"
    property var anotherString: String("#FF008800")
    property var aColor: Qt.rgba(0.2, 0.3, 0.4, 0.5)
    property var aRect: Qt.rect(10, 10, 10, 10)
    property var aPoint: Qt.point(10, 10)
    property var aSize: Qt.size(10, 10)
    property var aVector3d: Qt.vector3d(100, 100, 100)
    property var anArray: [1, 2, 3, "four", "five", (function() { return "six"; })]
    property var anObject: { "foo": 10, "bar": 20 }
    property var aFunction: (function() { return "one"; })
}

変更通知セマンティクス

var プロパティに割り当てられた JavaScript オブジェクトの通常のプロパティを変更しても、それらにアクセスするバインディングは更新されないことに注意することが重要です。以下の例では、wheels プロパティが変更されても、"text" プロパティに割り当てられたバインディングが再評価されることはないため、"The car has 4 wheels" と表示されます:

Item {
    property var car: new Object({wheels: 4})

    Text {
        text: "The car has " + car.wheels + " wheels";
    }

    Component.onCompleted: {
        car.wheels = 6;
    }
}

もしonCompletedハンドラが"car = new Object({wheels: 6})" 、carプロパティ自体が変更され、変更通知が発行されるため、テキストは「The car has 6 wheels」と更新されるでしょう。

プロパティ値の初期化セマンティクス

QMLの構文では、プロパティ値の初期化代入の右辺にある中括弧はバインディング代入を表すと定義されています。これは、var のプロパティを初期化するときに混乱する可能性があります。JavaScript では、空の中括弧は式ブロックか空のオブジェクト宣言のどちらかを表すからです。var プロパティを空のオブジェクト値に初期化したい場合は、中括弧を括弧で囲む必要があります。

var 型のプロパティは、デフォルトでundefined になります。

例えば

Item {
    property var first:  {}   // nothing = undefined
    property var second: {{}} // empty expression block = undefined
    property var third:  ({}) // empty object
}

前の例では、first プロパティは空の式にバインドされ、その結果は未定義です。second プロパティは、単一の空の式ブロック("{}")を含む式にバインドされており、同様に結果は未定義です。third プロパティは、空のオブジェクト宣言として評価される式にバインドされているため、プロパティはその空のオブジェクト値で初期化されます。

同様に、JavaScript のコロンはオブジェクト・プロパティ値の割り当てにもコード・ラベルにもなります。したがって、var プロパティをオブジェクト宣言で初期化する場合にも括弧が必要になります:

Item {
    property var first: { example: 'true' }    // example is interpreted as a label
    property var second: ({ example: 'true' }) // example is interpreted as a property
    property var third: { 'example': 'true' }  // example is interpreted as a property
    Component.onCompleted: {
        console.log(first.example) // prints 'undefined', as "first" was assigned a string
        console.log(second.example) // prints 'true'
        console.log(third.example) // prints 'true'
    }
}

QML 値の型参照してください

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.