简体   繁体   English

如何将Qt中的keyPressEvent传递给基类?

[英]How to pass keyPressEvent in Qt to base class?

The Qt documentation for the QWidget::keyPressEvent method says: QWidget :: keyPressEvent方法的Qt文档说:

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key. 如果重新实现此处理程序,那么如果不对键进行操作,则调用基类实现非常重要。

However, I'm not sure what code is used to make sure the keypress gets passed to the next object in line to process it. 但是,我不确定使用什么代码来确保将按键传递给下一个对象以对其进行处理。 I have a function void MainWindow::keyPressEvent(QKeyEvent *k) . 我有一个函数void MainWindow :: keyPressEvent(QKeyEvent * k) What do I put into the method if I am "do not act upon the key"? 如果我“不按钥匙操作”,该如何处理?

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key. 如果重新实现此处理程序,那么如果不对键进行操作,则调用基类实现非常重要。

In C++ if you want to call a base class method, you use the :: scoping operator to do so. 在C ++中,如果要调用基类方法,请使用::作用域运算符进行调用。 In the case to defer to the base class's implementation, just write: 为了顺应基类的实现,只需编写:

return QWidget::keyPressEvent(k);

That's what "call the base class implementation" means. 这就是“调用基类实现”的意思。

UPDATE: Fixed typo, to fix infinite loop. 更新:修正了错字,以修复无限循环。

mainwindow.h mainwindow.h

#include <QMainWindow>
#include <QKeyEvent>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget * parent = 0);
    ~MainWindow();
public slots:
    void keyPressEvent(QKeyEvent*);
    void keyReleaseEvent(QKeyEvent*);
//...
}

mainwindow.cpp mainwindow.cpp

#include <QDebug>
#include "mainwindow.h"

void MainWindow::keyPressEvent(QKeyEvent* ke)
{
        qDebug() << Q_FUNC_INFO;
        qDebug() << "mw" << ke->key() << "down";
        QMainWindow::keyPressEvent(ke); // base class implementation
}

void MainWindow::keyReleaseEvent(QKeyEvent* ke)
{
        qDebug() << Q_FUNC_INFO;
        qDebug() << "mw" << ke->key() << "up";
        if(ke->key() == Qt::Key_Back)// necessary for Q_OS_ANDROID
        {
                // Some code that handles the key press I want to use
                // Note: default handling of the key is skipped
                ke->accept();
                return;
        }
        else
        {
                // allow for the default handling of the key
                QMainWindow::keyReleaseEvent(ke); // aka the base class implementation
        }
}

Hope that helps. 希望能有所帮助。

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

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