翻譯|使用教程|編輯:龔雪|2022-10-08 10:03:52.297|閱讀 295 次
概述:本系列文章將為大家介紹如何使用Qt 6來(lái)構(gòu)建一個(gè)移動(dòng)應(yīng)用程序,歡迎持續(xù)關(guān)注獲取更多Qt中文教程!
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
Qt是目前最先進(jìn)、最完整的跨平臺(tái)C++開(kāi)發(fā)工具。它不僅完全實(shí)現(xiàn)了一次編寫,所有平臺(tái)無(wú)差別運(yùn)行,更提供了幾乎所有開(kāi)發(fā)過(guò)程中需要用到的工具。如今,Qt已被運(yùn)用于超過(guò)70個(gè)行業(yè)、數(shù)千家企業(yè),支持?jǐn)?shù)百萬(wàn)設(shè)備及應(yīng)用。
本教程介紹了在使用Qt 6作為最低Qt版本并使用CMake作為構(gòu)建系統(tǒng)時(shí),如何使用Qt Creator開(kāi)發(fā)適用于Android和iOS設(shè)備的Qt Quick應(yīng)用程序。(點(diǎn)擊這里回顧上文內(nèi)容>>)
當(dāng)您傾斜設(shè)備時(shí),應(yīng)用程序的主視圖會(huì)顯示一個(gè) SVG 氣泡圖像,該圖像會(huì)在屏幕上移動(dòng)。
我們?cè)诒窘坛讨惺褂?Bluebubble.svg,但您可以使用任何其他圖像或組件來(lái)代替。
要在運(yùn)行應(yīng)用程序時(shí)顯示圖像,您必須在向?qū)槟鷦?chuàng)建的 CMakeLists.txt 文件的 RESOURCES 部分中將其指定為資源:
qt_add_qml_module(appaccelbubble URI accelbubble VERSION 1.0 QML_FILES main.qml RESOURCES Bluebubble.svg )
我們通過(guò)添加一個(gè)以 Bluebubble.svg 作為源的 Image 組件在 main.qml 文件中創(chuàng)建主視圖:
Image { id: bubble source: "Bluebubble.svg" smooth: true
接下來(lái),我們添加自定義屬性以根據(jù)主窗口的寬度和高度定位圖像:
property real centerX: mainWindow.width / 2 property real centerY: mainWindow.height / 2 property real bubbleCenter: bubble.width / 2 x: centerX - bubbleCenter y: centerY - bubbleCenter
我們現(xiàn)在要添加代碼以根據(jù)加速度計(jì)傳感器值移動(dòng)氣泡。 首先,我們添加以下導(dǎo)入語(yǔ)句:
import QtSensors
接下來(lái),我們添加具有必要屬性的 Accelerometer 組件:
Accelerometer { id: accel dataRate: 100 active:true
然后,我們添加以下 JavaScript 函數(shù),這些函數(shù)根據(jù)當(dāng)前的 Accelerometer 值計(jì)算氣泡的 x 和 y 位置:
function calcPitch(x,y,z) { return -Math.atan2(y, Math.hypot(x, z)) * mainWindow.radians_to_degrees; } function calcRoll(x,y,z) { return -Math.atan2(x, Math.hypot(y, z)) * mainWindow.radians_to_degrees; }
我們?yōu)?Accelerometer 組件的 onReadingChanged 信號(hào)添加以下 JavaScript 代碼,以使氣泡在 Accelerometer 值發(fā)生變化時(shí)移動(dòng):
onReadingChanged: { var newX = (bubble.x + calcRoll(accel.reading.x, accel.reading.y, accel.reading.z) * .1) var newY = (bubble.y - calcPitch(accel.reading.x, accel.reading.y, accel.reading.z) * .1) if (isNaN(newX) || isNaN(newY)) return; if (newX < 0) newX = 0 if (newX > mainWindow.width - bubble.width) newX = mainWindow.width - bubble.width if (newY < 18) newY = 18 if (newY > mainWindow.height - bubble.height) newY = mainWindow.height - bubble.height bubble.x = newX bubble.y = newY }
我們要確保氣泡的位置始終在屏幕范圍內(nèi),如果加速度計(jì)返回的不是數(shù)字 (NaN),則忽略該值并且不更新氣泡位置。
我們?cè)跉馀莸?x 和 y 屬性上添加 SmoothedAnimation 操作,使其運(yùn)動(dòng)看起來(lái)更平滑。
Behavior on y { SmoothedAnimation { easing.type: Easing.Linear duration: 100 } } Behavior on x { SmoothedAnimation { easing.type: Easing.Linear duration: 100 } }
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)