Qt 按键事件

按键事件

按键事件是Qt提供的特有的事件体系,其头文件为QKeyEvent,这一篇我们通过一个demo演示按键事件,首先我们创建一个QApplication项目,创建类名为Widget,继承自QWidget,然后在ui里添加一个button。重写Widget的keyPressEvent函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Widget::keyPressEvent(QKeyEvent *event){
//判断是ctrl+M
if(event->modifiers() == Qt::ControlModifier){
if(event->key() == Qt::Key_M && windowState() != Qt::WindowFullScreen){
setWindowState(Qt::WindowFullScreen);
return;
}
return;
}

//如果按下的是ESC
if(event->key() == Qt::Key_Escape && windowState() == Qt::WindowFullScreen){
setWindowState(Qt::WindowNoState);
return;
}
}

在这个按键事件里,我们判断了是否按下控制键Ctrl,如果按下了控制键Ctrl并且按下M键,则进行之后的判断逻辑。
如果此时窗口并不是全屏,那么就将窗口设置为全屏,否则什么都不做。
如果按下的是ESC键,且此时窗口全屏,则将窗口设置为正常状态,非全屏。

控制按钮移动

我们可以通过上下左右键控制按钮移动,需求如下
1 当我们按住一个方向键时控制按钮朝一个方向移动
2 当我们同时按住两个方向键则让其朝着两个方向的中间移动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
void Widget::keyPressEvent(QKeyEvent *event){

bool b_upflag= false;
bool b_downflag = false;
bool b_leftflag = false;
bool b_rightflag = false;

if(event->key() == Qt::Key_Up){
if(event->isAutoRepeat()){
auto curpos = ui->pushButton->pos();
curpos.setY(curpos.y()-5);
ui->pushButton->move(curpos);
return;
}else{
b_upflag = true;
}

}

if(event->key() == Qt::Key_Left){
if(event->isAutoRepeat()){
auto curpos = ui->pushButton->pos();
curpos.setX(curpos.x()-5);
ui->pushButton->move(curpos);
return;
}else{
b_leftflag = true;
}
}


if(event->key() == Qt::Key_Down){
if(event->isAutoRepeat()){
auto curpos = ui->pushButton->pos();
curpos.setY(curpos.y()+5);
ui->pushButton->move(curpos);
return;
}else{
b_downflag = true;
}

}

if(event->key() == Qt::Key_Right){
if(event->isAutoRepeat()){
auto curpos = ui->pushButton->pos();
curpos.setX(curpos.x()+5);
ui->pushButton->move(curpos);
return;
}else{
b_rightflag = true;
}
}

auto curpos = ui->pushButton->pos();
if(b_upflag){
curpos.setY(curpos.y()-5);
}

if(b_downflag){
curpos.setY(curpos.y()+5);
}

if(b_leftflag){
curpos.setX(curpos.x()-5);
}

if(b_rightflag){
curpos.setX(curpos.x()+5);
}

ui->pushButton->move(curpos);

}

我们通过isAutoRepeat函数判断某一个按键是否被单一按下,如果是,则直接移动按钮的位置。
否则我们根据按键的方向设置对应的标记,最后根据标记设置按钮的位置,以达到朝着两个方向的中间移动的效果。

总结

源码链接:
https://gitee.com/secondtonone1/qt-learning-notes