Qt 帮助:Keyboard Focus in QML
QML项目获取焦点的属性:focus: true
QML项目在Qt传统的键盘焦点模型上天剑了基于作用域的扩展。
1. 按键处理概述
用户按下或释放一个按键,处理步骤:
1) Qt获取键盘动作并产生一个键盘事件
2) 如果包含QDeclaretiveView的Qt不见具有焦点,那么键盘事件会传递给它,否则将进行常规的按键处理
3) 场景将键盘事件交付给具体活动焦点的QML项目。如果没有项目具有活动焦点,键盘事件会被忽略,然后按常规的按键处理
4) 如果具有活动焦点的QML项目接收了该键盘事件,那么传播将停止
Text {
text: activeFocus ? "I have active focus!" : "I do not have active focus!"
}
5) 如果到达了根项目,该事件会被忽略而继续常规的Qt按键处理
所有基于Item的可见元素都可以通过Keys附加属性来进行按键处理,Keys附加属性提供了基本的处理器。
import QtQuick 2.4
Rectangle {
width: 100
height: 100
focus: true
Keys.onPressed: {
if(event.key == Qt.Key_A) //event.key捕获按下的按键,另外还有accept、isAutoRepeat、modifiers和text
console.log("Key A was pressed")
event.accpted = true //防止事件向上层传播
}
}
Qt帮助:Keys
KeyNavigation元素--附件属性,可以用来实现用方向键或者Tab键来进行项目的导航
属性:backtab、down、left、priority、right、tab、up等
import QtQuick 2.4
Grid {
width: 100; height:200
columns: 2
Rectangle{
id: topLeft
width: 50; height: 50
color: focus ? "red" : "lightgray"
focus: true
KeyNavigation.right: topRight
KeyNavigation.down: bottomLeft
}
Rectangle{
id: topRight
width: 50; height: 50
color: focus ? "red" : "lightgray"
focus: true
KeyNavigation.left: topLeft
KeyNavigation.down: bottomRight
}
Rectangle{
id: bottomLeft
width: 50; height: 50
color: focus ? "red" : "lightgray"
focus: true
KeyNavigation.right: bottomRight
KeyNavigation.up: topLeft
}
Rectangle{
id: bottomRight
width: 50; height: 50
color: focus ? "red" : "lightgray"
focus: true
KeyNavigation.left: bottomLeft
KeyNavigation.up: topRight
}
}
2. 查询活动焦点项目
Item::activeFocus属性:插口一个项目是否具有焦点
Text {
text: activeFocus ? "I have active focus!" : "I do not have active focus!"
}
3. 获取焦点和焦点作用域
项目设置 focus: true 获取焦点
import QtQuick 2.4
Rectangle{
id: widget
width: 500; height: 500
radius: 10; smooth: true
color: "lightsteelblue"
Text {id: label; anchors.centerIn: parent}
focus: true
Keys.onPressed: {
if(event.key == Qt.Key_A)
label.text = "Key A was pressed"
if(event.key == Qt.Key_B)
label.text = "Key B was pressed"
if(event.key == Qt.Key_C)
label.text = "Key C was pressed"
}
}
注意:当上面代码作为一个可重用或者可被导入的组件时,简单的使用focus属性无效。
MyWidget.qml
import QtQuick 2.0
FocusScope {
//FocusScope需要绑定到子项目的可视属性上
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"
if(event.key == Qt.Key_B)
label.text = "Key B was pressed"
if(event.key == Qt.Key_C)
label.text = "Key C was pressed"
}
}
}
重用Mywiget
import QtQuick 2.4
Rectangle{
id: widget
width: 240; height: 150
color:"white";
Column {
anchors.centerIn: parent; spacing: 15
MyWidget {
focus: true
color: "lightblue"
}
MyWidget {
color: "palegreen"
}
}
}
注意:FocusScope元素不是可视化元素,需要将它的子项目的属性暴露给它的父项目。布局和定位元素可以使用这些可见和样式属性来创建布局。此例没有将Rectangle的属性直接绑定到FocusScope上,那么Column元素就无法正确地显示两个部件。