1

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!

  • The `keyPressEvent()` function is a virtual function of `QWidget` class. You misused it in your `QObject` class. Replace `QObject` with `QWidget`, create it and try to press a key. – vahancho Nov 09 '22 at 11:22
  • I am afraid, you completely misunderstand how events work in Qt. And I am sorry but StackOverflow is not the right place for teaching basic stuff which is already described in documentation or in dozens of tutorials all over the web and youtube. Most importantly key press event is passed from the application object to the focused widget automatically. You do not need to call it yourself or connect it to a signal. In order to implement your own key press event handler, you need to `override` `keyPressEvent()` for `QWidget` and not for `QObject`. – HiFile.app - best file manager Nov 09 '22 at 11:23

1 Answers1

3

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.

Strive Sun
  • 5,988
  • 1
  • 9
  • 26