jeudi 23 août 2018

Debounce event filter in Qt

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 ;)

Aucun commentaire:

Enregistrer un commentaire