本文介绍了Qt 的 nativeEvent() 永远不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Qt 应用程序中接收 Windows 消息.我首先从 winEvent() 函数开始,但它从未被调用过,我在 Qt 5.4 中了解到建议使用 nativeEvent() 但是它也从未被调用过?以下是我的代码,它是一个简单的应用程序,我只想在插入 USB 设备时捕获像 WM_PAINT 这样的消息和系统消息.

I am trying to recieve windows messages in my Qt App. I first started with winEvent() function but it was never called and I learned in Qt 5.4 it is recommended to use nativeEvent()however it is also never called as well? The following is my code, it is bare bone application, I just want to catch messages like WM_PAINT and also system message when USB device is plugged in.

//mainwindow.h

// mainwindow.h

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

    bool nativeEvent(QByteArray & eventType, void * message, long * result);
};

//mainwindow.cpp

// mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

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

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::nativeEvent(QByteArray & eventType, void * message, long * result)
{
    MSG *msg = static_cast< MSG * >( message );
    // TODO: filter out or modify msg struct here
    // ...

    qDebug() << "Message recieved"; // it never comes here, never breaks in this function with debugger

    return false;
}

推荐答案

你的nativeEvent方法签名有误,应该是:

Your method signature for nativeEvent is wrong, it should be:

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

将 Q_DECL_OVERRIDE(或 C++11 中的 override 关键字)添加到方法声明中以捕获这些非常有用.

It's useful to add the Q_DECL_OVERRIDE (or override keyword in C++11) to the method declaration to catch these.

这篇关于Qt 的 nativeEvent() 永远不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:58