在 Qt 中获取 MouseMoveEvents
在我的程序中,我希望每当鼠标移动(即使它位于另一个窗口上方)时调用 mouseMoveEvent(QMouseEvent* event) 。
现在,在我的 mainwindow.cpp 文件中,我有:
void MainWindow::mouseMoveEvent(QMouseEvent* event) {
qDebug() << QString::number(event->pos().x());
qDebug() << QString::number(event->pos().y());
}
但这似乎只有当我在程序本身的窗口上单击并拖动鼠标时才会调用。我尝试
setMouseTracking(true);
在 MainWindow 的构造函数中调用,但这似乎没有做任何不同的事情(mouseMoveEvent 仍然仅在我按住鼠标按钮时调用,无论它在哪里)。全局跟踪鼠标位置的最简单方法是什么?
In my program, I'd like to have mouseMoveEvent(QMouseEvent* event) called whenever the mouse moves (even when it's over another window).
Right now, in my mainwindow.cpp file, I have:
void MainWindow::mouseMoveEvent(QMouseEvent* event) {
qDebug() << QString::number(event->pos().x());
qDebug() << QString::number(event->pos().y());
}
But this seems to only be called when I click and drag the mouse while over the window of the program itself. I've tried calling
setMouseTracking(true);
in MainWindow's constructor, but this doesn't seem to do anything differently (mouseMoveEvent still is only called when I hold a mouse button down, regardless of where it is). What's the easiest way to track the mouse position globally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在应用程序上使用事件过滤器。
定义并实现 bool MainWindow::eventFilter(QObject*, QEvent*)。例如,
在构建 MainWindows 时(或其他地方)安装事件过滤器。例如
You can use an event filter on the application.
Define and implement bool MainWindow::eventFilter(QObject*, QEvent*). For example
Install the event filter when the MainWindows is constructed (or somewhere else). For example
我遇到了同样的问题,由于我试图调用
this->update()
来在鼠标移动时重新绘制窗口,但什么也没有发生,这一事实进一步加剧了问题。您可以通过调用 setMouseTracking(true) 来避免创建事件过滤器,如 @Kyberias 所说。但是,这必须在视口上完成,而不是在主窗口本身上完成。 (更新也是如此)。
因此,在构造函数中,您可以添加一行
this->viewport()->setMouseTracking(true)
,然后覆盖mouseMoveEvent
而不是创建此过滤器并安装它。I had the same problem, further exacerbated by the fact that I was trying to call
this->update()
to repaint the window on a mouse move and nothing would happen.You can avoid having to create the event filter by calling
setMouseTracking(true)
as @Kyberias noted. However, this must be done on the viewport, not your main window itself. (Same goes for update).So in your constructor you can add a line
this->viewport()->setMouseTracking(true)
and then overridemouseMoveEvent
rather than creating this filter and installing it.