用例 - 在QML中集成JavaScript¶
如何在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函数¶
JavaScript 函数可以在 QML 项目上声明,如下例所示。这允许您使用项目 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表达式的完整文档。