简体   繁体   English

Qt MouseMove事件未在eventFilter()中捕获

[英]Qt MouseMove event not being caught in eventFilter()

It is simply not working. 它根本不起作用。 I have enabled mousetracking, then installed the event filter, everything is fine, except for MouseMove events. 我启用了鼠标跟踪,然后安装了事件过滤器,除了MouseMove事件之外,其他一切都很好。 Any assistance, please? 有什么帮助吗?

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

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

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

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if(event->type() == QEvent::MouseMove)
    {
        QMouseEvent *mEvent = (QMouseEvent*)event;
        qDebug() << mEvent->pos();
    }
    return false;
}

This line is quite strange, you ask this to filter himself 这条线很奇怪,您要求this自己过滤

installEventFilter(this);

I would'nt be surprised if Qt did simply ignore self-filtering events 如果Qt只是忽略了自过滤事件,我不会感到惊讶

Try this for detecting mouse move events in the central widget: 尝试执行以下操作以检测中央小部件中的鼠标移动事件:

centralWidget()->installEventFilter(this);
centralWidget()->setMouseTracking(true);

Or, for detecting mouse move events in the MainWidget, use setMouseTracking(true) on this and instead of adding an event filter, reimplement the mouseMoveEvent() protected function: 或者,在MainWidget检测鼠标移动事件,使用setMouseTracking(true)this和而不是添加事件过滤器,重新实现mouseMoveEvent()保护功能:

//In constructor:
setMouseTracking(true);

and

void MainWindow::mouseMoveEvent(QMouseEvent * event)
{
    //do stuff here

    event->reject(); //To avoid messing QMainWindow mouse behavior
}

this is another design issue of QT: eventFilter will not receive the event... UNLESS you override mouseMoveEvent and ignore the signal there. 这是QT的另一个设计问题:eventFilter将不会接收事件...除非您重写mouseMoveEvent并忽略那里的信号。

void mouseMoveEvent(QMouseEvent* e) override { e->ignore(); }

Now, eventFilter can be used... and this is often desirable because you might have some eventFilter class that you would like to use with multiple widgets. 现在,可以使用eventFilter ...这通常是理想的,因为您可能要使用多个小部件使用一些eventFilter类。

QMainWindow has centralWidget that is located over MainWindow area. QMainWindow具有位于MainWindow区域上方的centralWidget。 Try to add to MainWindow constructor this code 尝试将代码添加到MainWindow构造函数

ui->centralWidget->setMouseTracking(true);

Mouse events will come first to MainWindow and then to centralWidget. 鼠标事件将首先到达MainWindow,然后到CentralWidget。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM