I am trying to create a Qt game program, in which two players control two robots to move in a 2D map. I am doing this with QGraphicsView and I have gone this far:
void MainWindow::on_keyPressed(QKeyEvent* event)
{
if(event->key()==Qt::Key_Left)
movingBox_1->setX(-5+movingBox_1->x());
if(event->key()==Qt::Key_W)
movingBox_2->setY(-5+movingBox_2->y());
...//other movements
}
where movingBox_1
and movingBox_2
are rectangles in a QGraphicsScene. This works if I press only one key. If I press W
and left
at the same time, only one of which is executed (the first one). Is there any way to accomplish: "press left and W at the same time, and movingBox_1
and movingBox_2
move simultaneously to different directions as defined"?
Thanks in advance.
Update: as one comment has kindly pointed out that a similar question has been asked, the eventFilter seems like a possible workaround. But when I tried this method, I find that if I press left
and W
at the same time, two boxes wound be moving simultaneously, and if now I release one of them, say left
, then the whole thing would pause for a moment before movingBox_2
starts to move again. Clearly this affects the game experience (if it were a real game) very much. Is there any way to make these keypresses behave "independently", or at least seem to be "independent"?
Also, I noticed this question was also asked in this question, and the op mentioned this problem in a comment. But that comment hasn't had any replies. So I don't think their questions really solved my problem.