Search code examples
c++qtqkeyevent

How to detect multiple keys pressed at once


I am currently developing a small 2D game with Qt C++.

The problem is that I can't catch more than 3 key pressed at the same time. I need this because I want to play with 2–4 players on the same PC, and on the same keyboard.
If I don't find a solution, my players won't be able to play at the same time, and that's a problem, because it's a real time game.

I am using the basic keyPressEvent to catch key pressed. Then I store the keys in a QMap(int, bool), to know which key is pressed and not pressed.

I am also using a timer to treat the QMap values and do some actions when one or more keys are pressed.

The problem is when 3 keys are pressed and held down, and I press a 4th key, the 4th key is not caught, actually the program doesn't call keyPressEvent anymore.

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QtWidgets>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();

private:
    QTimer *timer;
    QMap<int, bool> keys;
    void keyPressEvent(QKeyEvent *event);
    void keyReleaseEvent(QKeyEvent *e);

private slots:
    void timerOutEvent();
};

#endif // WIDGET_H

Widget.cpp

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    timer = new QTimer();
    timer->setInterval(1000/60);
    timer->start();

    connect(timer, &QTimer::timeout, this, &Widget::timerOutEvent);
}

Widget::~Widget()
{

}

void Widget::timerOutEvent()
{
    QString txt = "";

    if(keys[Qt::Key_Up])
    {
        txt += "u";
    }
    if(keys[Qt::Key_Down])
    {
        txt += "d";
    }
    if(keys[Qt::Key_Left])
    {
        txt += "l";
    }
    if(keys[Qt::Key_Right])
    {
        txt += "r";
    }

    qDebug() << txt;
}

void Widget::keyReleaseEvent(QKeyEvent *event)
{
    keys[event->key()] = false;
    QWidget::keyReleaseEvent(event);
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    keys[event->key()] = true;
    QWidget::keyPressEvent(event);
}

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

Solution

  • The keyboard is not a big block of keys. The keyboard is composed by groups of keys.

    I explain:

    1. You can't press all the four following keys : , , , buttons at once.

    2. But you can, for example, press the following keys at the same time : A, W, Shift, Ctrl, , right +, Enter. It makes 8 keys.

    So to conclude, the keyboard is kind of multiple groups of keys.