Debounce event filter in Qt

Banadora Source

it's my first question here about Qt (usually internet and doc helps me alot)

I've installed a eventfilter on my app (in main.cpp), and I want this event filter to check the key pressed then redistribute it to lower functions (like moving an item on a QGraphicsScene),

This is working BUT, 5 times.. The qDebug() in filter shows me that the key is pressed 5 times when it was just one.

Event filter is so fast it catches it 5 times. Can't find a way to debounce that.

Here's the interesting parts of code:

main.cpp

#include "mainwindow.h"
#include "eventfilter.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    xEventFilter *filter = new xEventFilter(&a);
    a.installEventFilter(filter);

    xMainWindow w;
    w.show();

    return a.exec();
}

eventfilter.h

#ifndef EVENTFILTER_H
#define EVENTFILTER_H

#include <QObject>

class xEventFilter : public QObject
{
    Q_OBJECT

public:
    explicit xEventFilter(QObject *parent = nullptr);

protected:
    bool eventFilter(QObject *obj, QEvent *event) override;
};

#endif // EVENTFILTER_H

eventfilter.cpp

#include "eventfilter.h"
#include "editor.h"

#include <QKeyEvent>
#include <QDebug>

extern xEditor *editor;

xEventFilter::xEventFilter(QObject *parent) :
    QObject(parent)
{ }

bool xEventFilter::eventFilter(QObject *obj, QEvent *event)
{
    qDebug() << "Enter filter";

    if (event->type() != QEvent::KeyPress)
        return QObject::eventFilter(obj, event);

    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

    qDebug() << keyEvent->text();

    switch(keyEvent->key()) {
        case Qt::Key_Z: { editor->selection->moveSelection(keyEvent); }
        case Qt::Key_S: { editor->selection->moveSelection(keyEvent); }
        case Qt::Key_Q: { editor->selection->moveSelection(keyEvent); }
        case Qt::Key_D: { editor->selection->moveSelection(keyEvent); }
        case Qt::Key_Space: { }
    }

    return false;
}

Looking up to your answers ;)

c++qtc++11

Answers

answered 2 months ago Jaa-c #1

The main issue is that even if you handle the event, you return false. According to the documentation, you should return true if you want the event to stop being handled.

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

Also, you're missing break in cases of your switch statement.

comments powered by Disqus