在Qt C ++中使用多个键 [英] Using multiple keys in Qt C++
本文介绍了在Qt C ++中使用多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建坦克"游戏,在该游戏中,我使用Key事件在地图上运行我的坦克.实际上,我一次只能使用一个键,但是我需要具备f.e.同时向上和向左走.
I'm building the "Tanks" game where I'm using Key event to run my tank on map. Actually I can only use one key at the time but I need to have ability to f.e. go up and left simultaneously.
这是我的单键事件代码:
Here's my code for single key events:
switch(event->key())
{
case Qt::Key_Up:
if(!ui->widget->playerList[playerID]->canMove(0.3, 20, 20, -20, -20, 1.5)) return;
ui->widget->playerList[playerID]->move(0.3);
ui->widget->updateGL();
break;
case Qt::Key_Down:
if(!ui->widget->playerList[playerID]->canMove(-0.2, 20, 20, -20, -20, 1.5)) return;
ui->widget->playerList[playerID]->move(-0.2);
ui->widget->updateGL();
break;
case Qt::Key_Right:
ui->widget->playerList[playerID]->rotate(10);
ui->widget->updateGL();
break;
case Qt::Key_Left:
ui->widget->playerList[playerID]->rotate(-10);
ui->widget->updateGL();
break;
case Qt::Key_Q:
ui->widget->playerList[playerID]->rotateCannon(10);
ui->widget->updateGL();
break;
case Qt::Key_E:
ui->widget->playerList[playerID]->rotateCannon(-10);
ui->widget->updateGL();
break;
default:
QMainWindow::keyPressEvent(event);
break;
}
推荐答案
您可以将按键添加到按键组中,并在释放按键时从该按键组中删除.因此,您可以将按下的键添加到作为类成员的QSet中:
You can add a pressed key to the set of pressed keys and remove from this set when the key is released. So you can add the pressed key to a QSet which is a class member :
QSet<int> pressedKeys;
您可以在事件过滤器中捕获关键事件:
You can catch the key events in an event filter :
bool MyWidget::eventFilter(QObject * obj, QEvent * event)
{
if(event->type()==QEvent::KeyPress) {
pressedKeys += ((QKeyEvent*)event)->key();
f( pressedKeys.contains(Qt::Key_Up) && pressedKeys.contains(Qt::Key_Left) )
{
// up and left is pressed
}
}
else if(event->type()==QEvent::KeyRelease)
{
pressedKeys -= ((QKeyEvent*)event)->key();
}
return false;
}
不要忘记在构造函数中安装事件过滤器:
Don't forget to install the event filter in the constructor:
this->installEventFilter(this);
这篇关于在Qt C ++中使用多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文