翻譯|使用教程|編輯:龔雪|2022-03-21 10:02:57.510|閱讀 276 次
概述:本文主要介紹如何在QML中集成JavaScript,歡迎下載相關組件體驗~
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
JavaScript 代碼可以很容易地集成到 QML 中,以提供 UI 邏輯、命令式控制或其他。
JavaScript 表達式可以在 QML 中用作綁定,例如:
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技術交流群:166830288 歡迎一起進群討論
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@ke049m.cn
文章轉載自:慧都網