QMouseEvent 用于单机芯

QMouseEvent for single movement

本文关键字:单机芯 用于 QMouseEvent      更新时间:2023-10-16

为什么Qt鼠标移动事件为单个移动传递多个事件?

这是一个简单的项目。

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <fstream>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
// handle the pressing event to track the starting of the moving event
void mousePressEvent(QMouseEvent* ev);
void mouseMoveEvent(QMouseEvent* ev);
// handle the releasing event to track the end of the moving event
void mouseReleaseEvent(QMouseEvent* ev);
private:
std::ofstream fout; // open the file "debug.txt"
};
#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include <QMouseEvent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
fout.open("debug.txt"); // open the output file
}
MainWindow::~MainWindow()
{
fout.close(); // close the file when program closed
}
void MainWindow::mousePressEvent(QMouseEvent *ev)
{
ev->accept();
fout << "pressed at (" << ev->x() << ',' << ev->y() << ')' << std::endl;
}
void MainWindow::mouseMoveEvent(QMouseEvent *ev)
{
ev->accept();
fout << "moved to (" << ev->x() << ',' << ev->y() << ')' << std::endl;
}
void MainWindow::mouseReleaseEvent(QMouseEvent *ev)
{
ev->accept();
fout << "released at (" << ev->x() << ',' << ev->y() << ')' << std::endl;
}

主.cpp

#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}

"debug.txt"的结果以以下内容结束:

pressed at (106,26)
moved to (106,26)
moved to (105,26)
moved to (105,26)
released at (105,26)

我确定我小心翼翼地移动了鼠标,以确保我的鼠标只移动了一个像素,但Qt的事件提供程序传递了3个事件。 如果有人能解释原因将是一个很好的帮助。

发生这种情况是因为轮询鼠标位置而不考虑坐标,尤其是光标的屏幕坐标。它以希望定期的方式进行轮询。实际上,鼠标坐标是相对的,并以小于一毫米(或屏幕上的像素(为单位进行测量。将鼠标的三个独立位置转换为像素后,您收到了三次相同的坐标。