键盘事件
qml对键盘的处理,处理利用Keys,例如按键按下的处理:
pressed(KeyEvent event)
This signal is emitted when a key has been pressed. The event parameter provides information about the event. The corresponding handler is onPressed.
类似于Qt的keyPressEvent事件,在qml中也是一样,如果要处理按键按下,就调用Keys的onPressed, 在根据按键类型进行处理,代码如下:
Keys.onPressed: {
switch(event.key){
case Qt.Key_0:
case Qt.Key_1:
case Qt.Key_2:
case Qt.Key_3:
case Qt.Key_4:
case Qt.Key_5:
case Qt.Key_6:
case Qt.Key_7:
case Qt.Key_8:
case Qt.Key_9:
keyView.text = event.key - Qt.Key_0;
break;
}
}
鼠标点击事件
qml的鼠标类型是MouseArea,鼠标的点击要分清左右键,单击双击等。
示例代码下面给出键盘鼠标事件的示例代码:
/*
qml键盘鼠标事件
*/
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle
{
width: parent.width;
height: parent.height;
color: "#c0c0c0";
focus: true;
Keys.enabled: true;
Keys.onEscapePressed: Qt.quit();
Keys.onBackPressed: Qt.quit();
Keys.onPressed: {
switch(event.key){
case Qt.Key_0:
case Qt.Key_1:
case Qt.Key_2:
case Qt.Key_3:
case Qt.Key_4:
case Qt.Key_5:
case Qt.Key_6:
case Qt.Key_7:
case Qt.Key_8:
case Qt.Key_9:
keyView.text = event.key - Qt.Key_0;
break;
}
}
Text
{
id: keyView;
font.bold: true;
font.pixelSize: 24;
text: qsTr("text");
anchors.centerIn: parent;
}
}
Text {
id: helloworld;
anchors.left: parent.left;
anchors.leftMargin: 20
anchors.top: parent.top
anchors.topMargin: 20
text: qsTr("helloworld");
font{
bold: false;
pixelSize: 20;
}
Keys.onLeftPressed: x-=10;
Keys.onRightPressed: x+=10;
focus: true;//只有获得焦点的控件才能够响应鼠标事件
}
//鼠标事件处理
MouseArea{
anchors.fill: parent; //鼠标响应区域填充为整个区域
acceptedButtons: Qt.LeftButton|Qt.RightButton;
//响应单击事件
onClicked: {
if(mouse.button == Qt.LeftButton)
{
helloworld.text="clicked left";
}
else if(mouse.button == Qt.RightButton)
{
helloworld.text="clicked right";
}
}
//响应双击事件
onDoubleClicked: {
if(mouse.button == Qt.LeftButton){
helloworld.text="left double";
}
else if(mouse.button == Qt.RightButton)
{
helloworld.text="right double";
}
}
}
}
运行截图:
注意,键盘事件需要设置focus为true.