翻譯|使用教程|編輯:龔雪|2021-12-01 09:49:20.193|閱讀 259 次
概述:本文主要介紹如何在QML中響應(yīng)用戶輸入,歡迎下載框架產(chǎn)品體驗(yàn)~
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
Qt Quick 模塊支持最常見的用戶輸入類型,包括鼠標(biāo)和觸摸事件、文本輸入和按鍵事件,其他模塊為其他類型的用戶輸入提供支持。
本文介紹了如何處理基本的用戶輸入。
輸入處理程序讓 QML 應(yīng)用程序處理鼠標(biāo)和觸摸事件。 例如,您可以通過將 TapHandler 添加到 Image 或添加到其中包含 Text 對(duì)象的 Rectangle 來創(chuàng)建按鈕,TapHandler 響應(yīng)輕敲或點(diǎn)擊任何類型的定點(diǎn)設(shè)備。
import QtQuick Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" TapHandler { onTapped: rectangle.width += 10 } } }
注意:某些項(xiàng)目類型有自己的內(nèi)置輸入處理。 例如,F(xiàn)lickable 響應(yīng)鼠標(biāo)拖動(dòng)、輕觸和鼠標(biāo)滾輪滾動(dòng)。
來自設(shè)備、小鍵盤或鍵盤上的按鈕和按鍵都可以使用 Keys 附加屬性進(jìn)行處理,此附加屬性可用于所有 Item 派生類型,并與 Item::focus 屬性一起確定接收鍵事件的類型。 對(duì)于簡(jiǎn)單的鍵處理,您可以在單個(gè) Item 上將焦點(diǎn)設(shè)置為 true 并在那里進(jìn)行所有鍵處理。
import QtQuick Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" focus: true Keys.onUpPressed: rectangle.y -= 10 Keys.onDownPressed: rectangle.y += 10 Keys.onLeftPressed: rectangle.x += 10 Keys.onRightPressed: rectangle.x -= 10 } }
對(duì)于文本輸入,我們有多種 QML 類型可供選擇。 TextInput 提供無樣式的單行可編輯文本,而 TextField 更適合應(yīng)用程序中的表單字段。 TextEdit 可以處理多行可編輯文本,但 TextArea 是更好的選擇,因?yàn)樗砑恿藰邮健?
以下代碼段演示了如何在您的應(yīng)用程序中使用這些類型:
import QtQuick import QtQuick.Controls import QtQuick.Layouts ApplicationWindow { width: 300 height: 200 visible: true ColumnLayout { anchors.fill: parent TextField { id: singleline text: "Initial Text" Layout.alignment: Qt.AlignHCenter | Qt.AlignTop Layout.margins: 5 background: Rectangle { implicitWidth: 200 implicitHeight: 40 border.color: singleline.focus ? "#21be2b" : "lightgray" color: singleline.focus ? "lightgray" : "transparent" } } TextArea { id: multiline placeholderText: "Initial text\n...\n...\n" Layout.alignment: Qt.AlignLeft Layout.fillWidth: true Layout.fillHeight: true Layout.margins: 5 background: Rectangle { implicitWidth: 200 implicitHeight: 100 border.color: multiline.focus ? "#21be2b" : "lightgray" color: multiline.focus ? "lightgray" : "transparent" } } } }
Qt技術(shù)交流群4: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)