本页内容

在 QML 中集成 JavaScript

JavaScript 代码可以轻松集成到 QML 中,以提供用户界面逻辑、命令式控制或其他优势。

使用 JavaScript 表达式作为属性值

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

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

请注意,除非参数发生变化,否则诸如 Math.random() 之类的函数调用不会被重新评估。因此,绑定到 Math.random() 的值将是一个随机数且不会被重新评估;但如果宽度通过其他方式发生变化,高度的绑定值将会被重新评估以反映这一变化。

在 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 } }
    }

}

由 JavaScript 计算出的角度旋转的绿色正方形

有关 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.