Home > database >  KeyPressedEvent not registering
KeyPressedEvent not registering

Time:04-29

I am new to Qt and trying to implement what should be a pretty straightforward "key pressed" event method, but it doesn't seem to be registering properly.

Here is the declaration in my header file:

#include <Qt>
#include <QKeyEvent>

class MainWindow : public QMainWindow
{
    Q_OBJECT

protected:
    void KeyPressEvent(QKeyEvent* event);

};

and here is the implementation:

void MainWindow::KeyPressEvent(QKeyEvent *event)
{
    qDebug() << "Registered Key Press";
}

This is almost exactly what the examples I have seen online look like, so unless there is some connection somewhere I am missing, not sure what the issue would be.

CodePudding user response:

It is, as you say, almost exactly what the examples show. They should show

void keyPressEvent(QKeyEvent* event) override;

See QWidget::keyPressEvent. Note that C is case sensitive (K -> k).

Also, I've added the override keyword - then the compiler will tell you if you try to override a function which the compiler doesn't know!

Additional caveats are included in above linked documentation:

  • Make sure to call setFocusPolicy with an appropriate policy;

  • Note also that child widgets can "swallow" events. Meaning that if your main window has any children; and the key press happens inside a child, the child can say "I handle this event, no need to pass it on to my parent". Then your MainWindow::keyPressEvent also won't get called; see the corresponding notes in the QKeyEvent documentation; the gist: any child window of your MainWindow handling keyPressEvent has to ignore() the event in order for it to propagate to the parent class.

  •  Tags:  
  • c qt
  • Related