在Qt中获取MouseMoveEvents [英] Getting MouseMoveEvents in Qt
问题描述
在我的程序中,我希望每当鼠标移动(即使它在另一个窗口上)时都调用mouseMoveEvent(QMouseEvent *事件).
In my program, I'd like to have mouseMoveEvent(QMouseEvent* event) called whenever the mouse moves (even when it's over another window).
现在,在我的mainwindow.cpp文件中,我有:
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);
在MainWindow的构造函数中,但这似乎没有什么不同(mouseMoveEvent仍然仅在我按住鼠标按钮时才调用,无论它在哪里).全局跟踪鼠标位置的最简单方法是什么?
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?
推荐答案
您可以在应用程序上使用事件过滤器.
You can use an event filter on the application.
定义并实现布尔MainWindow :: eventFilter(QObject *,QEvent *).例如
Define and implement bool MainWindow::eventFilter(QObject*, QEvent*). For example
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseMove)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
statusBar()->showMessage(QString("Mouse move (%1,%2)").arg(mouseEvent->pos().x()).arg(mouseEvent->pos().y()));
}
return false;
}
在构造MainWindows(或其他位置)时安装事件过滤器.例如
Install the event filter when the MainWindows is constructed (or somewhere else). For example
MainWindow::MainWindow(...)
{
...
qApp->installEventFilter(this);
...
}
这篇关于在Qt中获取MouseMoveEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!