界面有输入事件的时候,难免会遇到多个地方需要输入,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 }