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 関数の追加
以下の例のように、QMLアイテム上でJavaScript関数を宣言できます。これにより、アイテム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 ファイルの使用
JavaScriptファイルを使用すると、QMLファイルからロジックを抽象化できます。これを行うには、まず示された例のように、関数を.jsファイル内に記述します。
// myscript.js
function getRandom(previousValue) {
return Math.floor(previousValue + Math.random() * 90) % 360;
}次に、以下の例のようなQMLファイルなど、その関数を使用する必要がある任意の.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式」の完全なドキュメントを参照してください。
© 2026 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.