Search code examples
c++windowsqtwinapiqt6

Why is nativeEvent not registering keystrokes?


I've set up my application to print a debug statement when clicking on F8 or F7 on my keyboard. However, nativeEvent doesn't seem to pick up on any keyboard input, why is this?

mainwindow.cpp snippet:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QKeySequence defaultKeySequence("F9");
    ui->keySequenceEdit->setKeySequence(defaultKeySequence);

    registerHotKey(100, 0, VK_F8);
    registerHotKey(101, 0, VK_F7);

}


bool MainWindow::registerHotKey(int id, int modifiers, int key) {
    if (!RegisterHotKey((HWND)MainWindow::winId(), id, modifiers, key)) {
        qDebug() << "Failed to register hotkey with ID:" << id;
        return false;
    }
    qDebug() << "Registered hotkey with ID:" << id;
    return true;
}


bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result){
    Q_UNUSED(eventType);
    Q_UNUSED(result);
    qDebug() << "Received message:";
    return false;
}

mainwindow.h snippet:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


    Ui::MainWindow *getUi() const;


protected:
    bool nativeEvent(const QByteArray &eventType, void *message, long *result);

private slots:
    // Stuff

private:
    Ui::MainWindow *ui;
};

Upon running the application, the output yields:

STARTING APPLICATION!
Hotkey changed to:  QKeySequence("F9")
Registered hotkey with ID: 100
Registered hotkey with ID: 101

When pressing F8 and F7, no debug output is displayed.


Solution

  • For Qt6 the signature of the method to override is:

    bool QWidget::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
    

    If on your platform std::is_same_v<qintptr, long> is false, then you are overloading or shadowing the method instead of overriding it. To avoid this kind of mistakes, it's a good practice to use override keyword:

    // this will result in compilation error:
    bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;