Problem with EventFilter and QEvent::KeyRelease event



  • Hi all,

    I'm having a problem using the eventfilter and the QEvent::KeyRelease event. In my desktop app I just want to know when a key from the keyboard has been released. Let's say I click the T key, I want to know when the key is released. this is my piece of code:

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
    //           qDebug() << "key " << keyEvent->key() << "from" << obj << "PRESSED";
               if(keyEvent->key() == Qt::Key_T)
               {
                  t_pressed = true;
               }
        }
        else if(event->type() == QEvent::KeyRelease)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
               qDebug() << "key " << keyEvent->key() << "from" << obj << " RELEASED";
               if(keyEvent->key() == Qt::Key_T)
               {
                   t_pressed = false;
               }
        }
        else if(event->type() == QEvent::ShortcutOverride)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
    //        qDebug() << "key " << keyEvent->key() << "from" << obj << "OVERRIDE";
        }
    
        return QObject::eventFilter(obj, event);
    }
    

    Now if I keep the button pressed, let's say for 2 seconds, I continuously get the QEvent::KeyRelease although I didn't release the key. That's strange, but in this way I cannot get the QEvent::KeyRelease in the right way, because if I keep the button pressed I always get the QEvent::KeyRelease .

    Am I missing something?
    Thanks in advance!



  • @davidesalvetti
    I am guessing from your description, assuming it is true/happens for you at least, is to do with auto-repeat when you hold a key down. Multiple key release events seems to be generated to signal up-level that the letter is auto-repeating. It may vary by person/platform, e.g. see https://stackoverflow.com/questions/48025384/qt-how-to-filter-keypressevent-with-autorepeat. The OP said it was happening to him, a respondent said he could not reproduce it, have a read.

    Anyway, if that really is the case, you will have no choice but to change code so that: clearly the only way to recognise will be when you do not get another key release (of same key) within the short auto-repeat period. You'll have to set a one-shot timer for that, reset on each key release: when it times out, the previous key release was the final genuine release.



  • Thanks for your answer, I was looking for a cleaner way to do it but using a QTimer works fine for now.
    Thanks again!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.