翻譯|使用教程|編輯:龔雪|2022-10-08 10:03:52.297|閱讀 311 次
概述:本系列文章將為大家介紹如何使用Qt 6來構(gòu)建一個移動應(yīng)用程序,歡迎持續(xù)關(guān)注獲取更多Qt中文教程!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
Qt是目前最先進、最完整的跨平臺C++開發(fā)工具。它不僅完全實現(xiàn)了一次編寫,所有平臺無差別運行,更提供了幾乎所有開發(fā)過程中需要用到的工具。如今,Qt已被運用于超過70個行業(yè)、數(shù)千家企業(yè),支持數(shù)百萬設(shè)備及應(yīng)用。
本教程介紹了在使用Qt 6作為最低Qt版本并使用CMake作為構(gòu)建系統(tǒng)時,如何使用Qt Creator開發(fā)適用于Android和iOS設(shè)備的Qt Quick應(yīng)用程序。(點擊這里回顧上文內(nèi)容>>)
當(dāng)您傾斜設(shè)備時,應(yīng)用程序的主視圖會顯示一個 SVG 氣泡圖像,該圖像會在屏幕上移動。
我們在本教程中使用 Bluebubble.svg,但您可以使用任何其他圖像或組件來代替。
要在運行應(yīng)用程序時顯示圖像,您必須在向?qū)槟鷦?chuàng)建的 CMakeLists.txt 文件的 RESOURCES 部分中將其指定為資源:
qt_add_qml_module(appaccelbubble URI accelbubble VERSION 1.0 QML_FILES main.qml RESOURCES Bluebubble.svg )
我們通過添加一個以 Bluebubble.svg 作為源的 Image 組件在 main.qml 文件中創(chuàng)建主視圖:
Image {
id: bubble
source: "Bluebubble.svg"
smooth: true
接下來,我們添加自定義屬性以根據(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ù)加速度計傳感器值移動氣泡。 首先,我們添加以下導(dǎo)入語句:
import QtSensors
接下來,我們添加具有必要屬性的 Accelerometer 組件:
Accelerometer {
id: accel
dataRate: 100
active:true
然后,我們添加以下 JavaScript 函數(shù),這些函數(shù)根據(jù)當(dāng)前的 Accelerometer 值計算氣泡的 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 信號添加以下 JavaScript 代碼,以使氣泡在 Accelerometer 值發(fā)生變化時移動:
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),如果加速度計返回的不是數(shù)字 (NaN),則忽略該值并且不更新氣泡位置。
我們在氣泡的 x 和 y 屬性上添加 SmoothedAnimation 操作,使其運動看起來更平滑。
Behavior on y {
SmoothedAnimation {
easing.type: Easing.Linear
duration: 100
}
}
Behavior on x {
SmoothedAnimation {
easing.type: Easing.Linear
duration: 100
}
}
Qt技術(shù)交流群:166830288 歡迎一起進群討論
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@ke049m.cn
文章轉(zhuǎn)載自:慧都網(wǎng)