0
votes

The Qt documentation for the QWidget::keyPressEvent method says:

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). What do I put into the method if I am "do not act upon the key"?

2

2 Answers

2
votes

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. 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.

2
votes

UPDATE: Fixed typo, to fix infinite loop.

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

#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.