qt eventfilter keypress does nothing

1.4k Views Asked by At

I started working with QT and want to program a little game named Pong ( 2 player and a ball). The left player should be moved with the keys 'W' and 'S', the right player with the arrow keys up and down. I have a class Game to handle my animation. There I have an eventfilter to handle the keyPress

bool Game::eventFilter(QObject *target, QEvent *e)
{
    Q_UNUSED(target);

    bool handled = false;
    if(e->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = (QKeyEvent *)e;

        if(keyEvent->key() == Qt::Key_W)
        {
            leftPlayerDir = ((leftPlayerDir == 0) ? 5 : leftPlayerDir);
            handled = true;
        }
        else if(keyEvent->key() == Qt::Key_S)
        {
            leftPlayerDir  = ((leftPlayerDir == 0) ? -5 : leftPlayerDir);
            handled = true;
        }
        else if(keyEvent->key() == Qt::Key_Up)
        {
            rightPlayerDir  = ((rightPlayerDir == 0) ? 5 : rightPlayerDir);
            handled = true;
        }
        else if(keyEvent->key() == Qt::Key_Down)
        {
            rightPlayerDir  = ((rightPlayerDir == 0) ? -5 : rightPlayerDir);
            handled = true;
        }
    }
     return handled;
}

and in my class Pong, where I set up the Mainwindow and handle the buttons, I have a line to install the eventfilter

ui->animation->installEventFilter(game);

If I start my program the animation is working, but the players are not moving on keyPress and I don't know why. Some ideas?

0

There are 0 best solutions below