使用例 - QMLにJavaScriptを組み込む

JavaScriptのコードをQMLに組み込むことで、UIロジックや命令制御、その他の利点を簡単に得ることができます。

JavaScriptの式をプロパティ値に使用する

QMLではJavaScriptの式をバインディングとして使用することができます。例えば

Item {
    width: Math.random()
    height: width < 100 ? 100 : (width + 50) /  2
}

Math.random()のような関数呼び出しは、引数が変化しない限り再評価されないことに注意してください。そのため、Math.random()へのバインディングは1つの乱数となり再評価されませんが、幅が他の方法で変更された場合、高さのバインディングはそれを考慮して再評価されます。

QMLにおけるJavaScript関数の追加

以下の例のように、JavaScriptの関数をQMLのアイテム上で宣言することができます。これにより、アイテムIDを使ってメソッドを呼び出すことができます。

import QtQuick

Item {
    id: container
    width: 320
    height: 480

    function randomNumber() {
        return Math.random() * 360;
    }

    function getNumber() {
        return container.randomNumber();
    }

    TapHandler {
        // This line uses the JS function from the item
        onTapped: rectangle.rotation = container.getNumber();
    }

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

JavaScriptファイルの利用

QMLファイルからロジックを抽象化するためにJavaScriptファイルを使うことができます。これを行うには、まず.jsファイルに関数を記述します。

// myscript.js
function getRandom(previousValue) {
    return Math.floor(previousValue + Math.random() * 90) % 360;
}

そして、そのファイルを、その関数を使用する必要のある.qmlファイルにインポートします。

import QtQuick
import "myscript.js" as Logic

Item {
    width: 320
    height: 480

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    TapHandler {
        // This line uses the JS function from the separate JS file
        onTapped: rectangle.rotation = Logic.getRandom(rectangle.rotation);
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

QMLで使用されているJavaScriptエンジンの詳細や、ブラウザJSとの違いについては、QMLドキュメントにおけるJavaScript表現についてをご覧ください。

© 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.