c++qtqmouseevent

QMouseEvent for single movement


Why Qt mouse movement event passing multiple event for a single movement?

Here is a simple project.

mainwindow.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

mainwindow.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;
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

the result of "debug.txt" ends with this content:

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

I'm sure I carefully moved my mouse to insure my mouse was moved only one single pixel but there is 3 event passed by the event provider of Qt. If anyone can explain the reason will be a good help.


Solution

  • It happens because mouse position is polled with no regard to coordinates, especially screen coordinates of cursor. It's polled in hopefully periodic manner. In reality, mouse coordinates are relative and measure in units way smaller than one millimeter (or pixel on screen). After converting three separate position of mouse to pixels, you had received same coordinates thrice.