翻譯|使用教程|編輯:龔雪|2021-12-01 09:49:20.193|閱讀 259 次
概述:本文主要介紹如何在QML中響應用戶輸入,歡迎下載框架產品體驗~
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Qt Quick 模塊支持最常見的用戶輸入類型,包括鼠標和觸摸事件、文本輸入和按鍵事件,其他模塊為其他類型的用戶輸入提供支持。
本文介紹了如何處理基本的用戶輸入。
輸入處理程序讓 QML 應用程序處理鼠標和觸摸事件。 例如,您可以通過將 TapHandler 添加到 Image 或添加到其中包含 Text 對象的 Rectangle 來創建按鈕,TapHandler 響應輕敲或點擊任何類型的定點設備。
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 } } }
注意:某些項目類型有自己的內置輸入處理。 例如,Flickable 響應鼠標拖動、輕觸和鼠標滾輪滾動。
來自設備、小鍵盤或鍵盤上的按鈕和按鍵都可以使用 Keys 附加屬性進行處理,此附加屬性可用于所有 Item 派生類型,并與 Item::focus 屬性一起確定接收鍵事件的類型。 對于簡單的鍵處理,您可以在單個 Item 上將焦點設置為 true 并在那里進行所有鍵處理。
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 } }
對于文本輸入,我們有多種 QML 類型可供選擇。 TextInput 提供無樣式的單行可編輯文本,而 TextField 更適合應用程序中的表單字段。 TextEdit 可以處理多行可編輯文本,但 TextArea 是更好的選擇,因為它添加了樣式。
以下代碼段演示了如何在您的應用程序中使用這些類型:
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技術交流群4:166830288 歡迎一起進群討論
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都網