用例 - 在 QML 中集成 JavaScript

JavaScript 代码可以轻松集成到 QML,以提供 UI 逻辑、命令式控制或其它好处。

对特性值使用 JavaScript 表达式

JavaScript 表达式可以在 QML 中作为绑定使用。例如:

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

Note that function calls, like Math.random(), will not be revaluated unless their arguments change. So binding to Math.random() will be one random number and not revaluated, but if the width is changed in some other manner, the height binding will be reevaluated to take that into account.

在 QML 中添加 JavaScript 函数

JavaScript functions can be declared on QML items, like in the below example. This allows you to call the method using the item id.

import QtQuick 2.3
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 } }
    }
}
					
					

使用 JavaScript 文件

JavaScript files can be used for abstracting out logic from QML files. To do this, first place your functions inside a .js file like in the example shown.

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

Then import the file into any .qml file that needs to use the functions, like the example QML file below.

import QtQuick 2.3
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 } }
    }
}
					

For further details on the JavaScript engine used by QML, as well as the difference from browser JS, see the full documentation on 在 QML 文档中的 JavaScript 表达式 .