翻譯|使用教程|編輯:龔雪|2022-03-21 10:02:57.510|閱讀 268 次
概述:本文主要介紹如何在QML中集成JavaScript,歡迎下載相關(guān)組件體驗(yàn)~
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷(xiāo)售中 >>
相關(guān)鏈接:
JavaScript 代碼可以很容易地集成到 QML 中,以提供 UI 邏輯、命令式控制或其他。
JavaScript 表達(dá)式可以在 QML 中用作綁定,例如:
Item { width: Math.random() height: width < 100 ? 100 : (width + 50) / 2 }
請(qǐng)注意,函數(shù)調(diào)用,如 Math.random(),不會(huì)被重新評(píng)估,除非它們的參數(shù)發(fā)生變化。 所以綁定到 Math.random() 將是一個(gè)隨機(jī)數(shù)并且不會(huì)重新計(jì)算,但如果寬度以其他方式改變,高度綁定將被重新計(jì)算以考慮到這一點(diǎn)。
可以在QML項(xiàng)目上聲明JavaScript函數(shù),如下例所示,這允許您使用項(xiàng)目ID調(diào)用該方法。
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 文件中抽象出邏輯。 為此,首先將您的函數(shù)放入 .js 文件中,如示例所示。
// myscript.js function getRandom(previousValue) { return Math.floor(previousValue + Math.random() * 90) % 360; }
然后將該文件導(dǎo)入到任何需要使用這些函數(shù)的 .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技術(shù)交流群:166830288 歡迎一起進(jìn)群討論
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:慧都網(wǎng)