keypress.h
#ifndef KEYPRESS_H
#define KEYPRESS_H
#include <QObject>
#include <QKeyEvent>
class keypress : public QObject {
Q_OBJECT public:
explicit keypress(QObject *parent = nullptr);
void keyPressEvent(QKeyEvent *e);
};
#endif // KEYPRESS_H
keypress.cpp
#include "keypress.h"
#include <QDebug>
keypress::keypress(QObject *parent)
: QObject{parent}
{
}
void keypress::keyPressEvent(QKeyEvent *e)
{
qDebug() <<"Key clicked : "<<e->key();
}
I am new to QKeyEvent and I am not able to call the keyPressEvent function. Should i call the keyPressEvent function inside the constructor? I also have to display a connect with keyPressEvent function and a timer of 50 milli seconds even if it doesn't receive any keypress. Thanks in Advance!
If you want to implement keyPressEvent in the widget/dialog/control, you can override keyPressEvent
.
Here is another link:
if you want to implement key press yourself and installed on other widgets
, you can refer to the code below,
From QObject::installEventFilter,
class KeyPressEater : public QObject
{
Q_OBJECT
...
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
};
bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug("Ate key press %d", keyEvent->key());
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
And here's how to install it on two widgets:
KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
QListView *listView = new QListView(this);
pushButton->installEventFilter(keyPressEater);
listView->installEventFilter(keyPressEater);
Hope it helps you.