QML ---- Keyboard Focus in QML --- 鍵盤交互

當一個鍵被按或者釋放的時候,一個Key事件就被創建並且傳遞給當前 QML中焦點Item。

 

1. 按鍵處理概述

當用戶按或者釋放一個按鍵的時候,如下將發生:

  • QT 接受到按鍵動作,並且產生一個按鍵事件
  • 如果QT 包含有 QDeclarativeView Widget 有焦點, 那麼key事件傳遞給他, 否則例行Key處理繼續
  • 如果沒有一個Item有active focus, 那麼key事件被忽略, 例行Key處理繼續
  • 如果一個active focus的item 接受了key 事件, 那麼Key事件的“遺傳”停止。否則, Key事件將冒泡一樣遞歸的往父Item傳遞, 直到事件被接收或者到根Item
  • 如果根Item到達,按鍵事件將被忽略, 例行按鍵處理繼續

2. 獲取focus以及focus scope

  一下代碼爲MyWidget.qml, 是一個長條,當按鍵A/B/C改變長條的TEXT。

  Rectangle { color: "lightsteelblue"; width: 240; height: 25 Text { id: myText } Item { id: keyHandler focus: true Keys.onPressed: { if (event.key == Qt.Key_A) myText.text = 'Key A was pressed' else if (event.key == Qt.Key_B) myText.text = 'Key B was pressed' else if (event.key == Qt.Key_C) myText.text = 'Key C was pressed' } } } 

將以上QML作爲一個組件,用於別的QML, 如:

  //Window code that imports MyWidget Rectangle { id: window color: "white"; width: 240; height: 150 Column { anchors.centerIn: parent; spacing: 15 MyWidget { focus: true //set this MyWidget to receive the focus color: "lightblue" } MyWidget { color: "palegreen" } } } 

運行結果如下:

QML <wbr>---- <wbr>Keyboard <wbr>Focus <wbr>in <wbr>QML <wbr>--- <wbr>鍵盤交互

看看上面的代碼,顯然存在一個明顯的問題:

有三個元素設置focus屬性爲true, 兩個MyWidget分別設置focus爲true, window組件也設置focus.事實上,僅僅只有一個元素可以獲得鍵盤焦點, 系統不得不去決定哪個元素該獲得焦點。

 

問題變得很清晰了。MyWidget組件將獲得焦點,但是它不能控制當他重用或者導入的時候的focus, 同樣,window組件也沒有能力知道是否它裏面導入的組件正請求focus.

 

爲解決這個問題, QML推出了一個概念,叫focus scope, 一個focus scope就像focus的代理。一個focus scope用FocusScope來表示。

 

修改MyWidget組件如下:

  FocusScope { //FocusScope needs to bind to visual properties of the Rectangle property alias color: rectangle.color x: rectangle.x; y: rectangle.y width: rectangle.width; height: rectangle.height Rectangle { id: rectangle anchors.centerIn: parent color: "lightsteelblue"; width: 175; height: 25; radius: 10; smooth: true Text { id: label; anchors.centerIn: parent } focus: true Keys.onPressed: { if (event.key == Qt.Key_A) label.text = 'Key A was pressed' else if (event.key == Qt.Key_B) label.text = 'Key B was pressed' else if (event.key == Qt.Key_C) label.text = 'Key C was pressed' } } } 
發佈了25 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章