简体   繁体   English

实现了 QKeyEvent 但如何调用 keyPressEvent()

[英]Implemented a QKeyEvent but how does the keyPressEvent() gets called

keypress.h按键.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按键.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?我是 QKeyEvent 的新手,我无法调用 keyPressEvent function。我应该在构造函数中调用 keyPressEvent function 吗? 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.我还必须显示与 keyPressEvent function 的连接和 50 毫秒的计时器,即使它没有收到任何按键。 Thanks in Advance!提前致谢!

If you want to implement keyPressEvent in the widget/dialog/control, you can override keyPressEvent .如果你想在小部件/对话框/控件中实现 keyPressEvent,你可以覆盖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,如果你想自己实现按键并安装在其他widgets上,你可以参考下面的代码,

From QObject::installEventFilter ,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.希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM