附网址:http://qt-project.org/doc/qt-5/qtquick-usecase-integratingjs.html
Use Case - Integrating JavaScript in QML—— 在QML中集成JavaScript代码
JavaScript代码可以很容易被集成到QML中以提供UI逻辑,必要的控制,或是其他益处。
Using JavaScript Expressions for Property Values —— 使用JavaScript表达式表示属性值
JavaScript表达式可以在QML中用作属性绑定。例如:
Item {
width: Math.random()
height: width < 100 ? 100 : (width + 50) / 2
}
·
注意到类似Math.random()这样的函数调用,除非它们的参数改变,否则不会被重新评估。因此这里width绑定的Math.random()只会得到一次随机值,而不会被反复评估。但如果宽度在某种情况下被改变,height属性的值由于绑定将被重新计算。
Adding JavaScript Functions in QML —— 在QML中添加JavaScript函数
JavaScript函数可能在QML组件中声明,类似下面的例子。你可以使用组件的id来调用这个方法。
import QtQuick 2.0
Item {
id: container
width: 320
height: 480
function randomNumber() {
return Math.random() * 360;
}
function getNumber() {
return container.randomNumber();
}
MouseArea {
anchors.fill: parent
// This line uses the JS function from the item
onClicked: 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 } }
}
}
·
Using JavaScript files —— 使用独立的JavaScript文件
JavaScript文件可以被用来为QML文件的抽象逻辑服务,将你的函数放置在一个.js文件中,像下面这样:
// myscript.js
function getRandom(previousValue) {
return Math.floor(previousValue + Math.random() * 90) % 360;
}
·
然后将这个文件引入到任何需要使用这个函数的.qml文件,像下面这样:
import QtQuick 2.0
import "myscript.js" as Logic
Item {
width: 320
height: 480
Rectangle {
color: "#272822"
width: 320
height: 480
}
MouseArea {
anchors.fill: parent
// This line uses the JS function from the separate JS file
onClicked: 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的区别,请到Using JavaScript Expressions with QML查看完整文档。