界面有輸入事件的時候,難免會遇到多個地方需要輸入,QT在focus上面有個類型需要了解:
下面看一下官方文檔給我們的例子我修改了一下:
Rectangle { id: window color: "white"; width: 240; height: 150 Column { anchors.centerIn: parent; spacing: 15 MyModules.MyFocusScope { //focus: true //set this MyWidget to receive the focus color: "lightblue" Component.onCompleted: { console.log("first Scope :", focus) }//在部件加載完成的時候打印focus狀態 }
MyModules.MyFocusScope {
focus: true
color: "palegreen"
Component.onCompleted: {
console.log("second Scope :", focus)
}
MyModules.MyFocusScope { color: "yellow" Component.onCompleted: { console.log("third Scope :", focus) } } } }
import QtQuick 2.0 Rectangle { id: widget color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: 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' } }
//在文件夾MyModules下有MyFocusScope.qml
log:
qml: third Scope : false
qml: second Scope : false
qml: first Scope : true
上面始終是第一個部件有鍵盤按下的提示,其他兩個就沒有,程序上寫了第二個是設置了true的再看log,發現focus始終是第一個部件是true。
外面的Rectangle不能控制部件的focus屬性。
QT里面提供了解決的方案:
使用 FocusScope 。需要注意的是 FocusScope 不是一個虛類型,子類型需要把屬性暴露給它。就是把子類型的屬性alias出來,做一個封裝,外部模塊再設置屬性的時候可以直接通過alias的屬性來設置它的子類型。下面是官方文檔給的例子。
1 FocusScope { 2 3 id: scope 4 5 //FocusScope needs to bind to visual properties of the children 6 property alias color: rectangle.color //把子類型的屬性拿出來。這樣做好了封裝 7 x: rectangle.x; y: rectangle.y 8 width: rectangle.width; height: rectangle.height 9 10 Rectangle { 11 id: rectangle 12 anchors.centerIn: parent 13 color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: true 14 Text { id: label; anchors.centerIn: parent } 15 focus: true 16 Keys.onPressed: { 17 if (event.key == Qt.Key_A) 18 label.text = 'Key A was pressed' 19 else if (event.key == Qt.Key_B) 20 label.text = 'Key B was pressed' 21 else if (event.key == Qt.Key_C) 22 label.text = = 'Key C was pressed' 23 } 24 } 25 MouseArea { anchors.fill: parent; onClicked: { scope.focus = true } }//這里就是把焦點調整過 26 }