用例 - 在 QML 中集成 JavaScript
JavaScript 代码可轻松集成到 QML 中,以提供 UI 逻辑、命令式控制或其他好处。
为属性值使用 JavaScript 表达式
JavaScript 表达式可在 QML 中用作绑定。例如
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 } } } }
有关 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.