JavaScript 代码可以很容易地集成到 QML 中,以提供 UI 逻辑、命令式控制或其他。
JavaScript 表达式可以在 QML 中用作绑定,例如:
?
class="prettyprint lang-js">Item {
width: Math.random()
height: width < 100 ? 100 : (width + 50) / 2
}
?
请注意,函数调用,如 Math.random(),不会被重新评估,除非它们的参数发生变化。 所以绑定到 Math.random() 将是一个随机数并且不会重新计算,但如果宽度以其他方式改变,高度绑定将被重新计算以考虑到这一点。
可以在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 文件可用于从 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 } }
}
}
?
 用户界面开发框架Qt 6.x入门级教程:用例 - 在QML中集成JavaScript">
用户界面开发框架Qt 6.x入门级教程:用例 - 在QML中集成JavaScript">
Qt技术交流群:166830288??????欢迎一起进群讨论