0

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"?

John
  • 640
  • 2
  • 8
  • 18

2 Answers2

2

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

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.

phyatt
  • 18,472
  • 5
  • 61
  • 80
  • Does calling MainWondow::keypressevent from MainWindow::keypressevent not result in an infinite loop? How does the program differentiate between my defined method and the base class's method? Something new for me to learn! – John Nov 24 '14 at 05:48
  • Sorry, you are right. That was a typo. It should be the base class of what you subclassed. So if you subclass QMainWindow, it should say QMainWindow. If you subclass QWidget, it should say QWidget, etc. – phyatt Nov 24 '14 at 06:53
  • http://stackoverflow.com/questions/15853031/call-base-class-method-from-derived-class-object – phyatt Nov 24 '14 at 06:54
  • Shouldn't the last code line be QMainWindow::keyReleaseEvent(ke); ? – lightdee Mar 12 '18 at 15:35
  • Yes. That looks like a typo on my part. – phyatt Mar 12 '18 at 15:36