鼠标事件
在QML中如果一个元素想要处理鼠标事件,则要放置一个MouseArea元素,即用户只能在MouseArea确定的范围内进行鼠标的动作
Rectangle{
width: 50;height: 50
color: "blue"
MouseArea{
anchors.fill: parent //事件响应充满整个矩形
//设置拖拽属性
drag.target: parent //指定被拖拽的元素
drag.axis: Drag.XAxis //设置拖拽方向
drag.minimumX: 0
drag.maximumX: 360 - parent.width //设置拖拽范围
acceptedButtons: Qt.LeftButton | Qt.RightButton//设置拖拽按键
onClicked: {
if(mouse.button === Qt.LeftButton){
parent.color = "red";
parent.width -= 5;
parent.height -= 5;
}else if(mouse.button === Qt.RightButton){
parent.color = "green";
parent.width += 5;
parent.height += 5;
}
}
}
}
键盘事件
Row{
x: 50
y: 100
spacing: 20
Rectangle{
id: music
radius: 6
width: 50
height: 50
color: focus ? "purple" : "lightgray"
scale: focus ? 1 : 0.8
focus: true //初始时选择音乐图标
KeyNavigation.tab: game //按下tab键将焦点转移到游戏图标
Keys.onUpPressed: music.y -= 10
Keys.onDownPressed: music.y += 10
Keys.onLeftPressed: music.x -= 10
Keys.onRightPressed: music.x += 10
Text{
text: "音乐"
font.bold: true
font.pointSize: 20
color: focus ? "black" : "gray"
anchors.centerIn: parent
}
}
Rectangle{
id: game
radius: 6
width: 50
height: 50
color: focus ? "purple" : "lightgray"
scale: focus ? 1 : 0.8
KeyNavigation.tab: vedio //按下tab键将焦点转移到视频图标
Keys.onUpPressed: game.y -= 10
Keys.onDownPressed: game.y += 10
Keys.onLeftPressed: game.x -= 10
Keys.onRightPressed: game.x += 10
Text{
text: "游戏"
font.bold: true
font.pointSize: 20
color: focus ? "black" : "gray"
anchors.centerIn: parent
}
}
Rectangle{
id: vedio
radius: 6
width: 50
height: 50
color: focus ? "purple" : "lightgray"
scale: focus ? 1 : 0.8
KeyNavigation.tab: music //按下tab键将焦点转移到音乐图标
Keys.onUpPressed: vedio.y -= 10
Keys.onDownPressed: vedio.y += 10
Keys.onLeftPressed: vedio.x -= 10
Keys.onRightPressed: vedio.x += 10
Text{
text: "视频"
font.bold: true
font.pointSize: 20
color: focus ? "black" : "gray"
anchors.centerIn: parent
}
}
}
输入控件与焦点
自定义组件代码如下,将自定义组件置于FocusScope元素中是为了能有效地控制焦点,它接收到焦点时,会将焦点交给最后一个设置了focus:true的子对象,就不会使焦点被父对象夺去了
FocusScope{
property alias label: label.text
property alias text: input.text
Row{
spacing: 10
Text{ //输入提示文本
text: "标签"
id: label
}
Rectangle{
width: 100
height: 20
color: "white"
border.color: "gray"
TextInput{ //文本输入框
id: input
anchors.fill: parent
anchors.margins: 4
focus: true //捕捉焦点
text: "请输入内容" //初始文本
}
}
}
}
Focus{ //学号文本框
id: tBx1
x: 50
y: 200
focus: true
label: "学号"
text: focus ? "" : "请输入内容"
KeyNavigation.tab: tBx2 //将焦点转移至姓名文本框
}
Focus{ //姓名文本框
id: tBx2
x: 50
y: 300
text: focus ? "" : "请输入内容"
KeyNavigation.tab: tBx1 //将焦点转移至学号文本框
}