关于c ++:如何将Qt中的keyPressEvent传递给基类?

How to pass keyPressEvent in Qt to base class?

the documentation QT keypressevent method for the QWidget说:::P></

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.

不管一个人多,我不可能做什么used to the code is sure to the next按键得到passed to process对象处理它。有一个空的函数:主窗口:keypressevent(qkeyevent×K)。给我一把"Do not if I AM法法"the key"?P></


更新:修正打字错误,修正无限循环。

主窗口.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <QMainWindow>
#include <QKeyEvent>

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

主窗口.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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
        }
}

希望有帮助。


If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.

在C++中,如果要调用基类方法,则使用EDCOX1×0的范围操作符来执行此操作。如果要遵从基类的实现,只需编写:

1
return QWidget::keyPressEvent(k);

这就是"调用基类实现"的含义。