0

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.

BugFinder
  • 1
  • 2
  • Possible duplicate of [Qt multiple key combo event](https://stackoverflow.com/questions/3081091/qt-multiple-key-combo-event) – Dmitry Sokolov Jul 16 '19 at 12:10
  • Thank you for this. I tried its solution just now. Unfortunately, it only solved part of my problem. It results in a small pause between different key combo events. I wasn't expect a solution to behave like this so I didn't mention it in my original answer. I have updated my question to include more details. – BugFinder Jul 16 '19 at 13:02
  • I think, you should ask another question about the lag between key events, i.e. keydown1, keydown2, keyup2, pause, other events. – Dmitry Sokolov Jul 16 '19 at 17:02
  • Have you tried QKeyEvent::matches instead of QKeyEvent::key? I don't have time to code and check this right now, but if there's potentially multiple keys down at a time, I think this may help you. – goug Jul 16 '19 at 23:59

0 Answers0