Qt Mouse Speed Calculation Guide

In Qt, you can calculate the mouse movement speed by capturing the mouse move event. First, you need to override the mouse move event handling method in your window or QWidget subclass.

void YourWidget::mouseMoveEvent(QMouseEvent *event)
{
    static QPoint lastPos;
    static qint64 lastTime = 0;

    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    QPoint currentPos = event->pos();

    if (lastTime == 0) {
        lastTime = currentTime;
        lastPos = currentPos;
        return;
    }

    int deltaTime = currentTime - lastTime;
    int distance = (currentPos - lastPos).manhattanLength();
    int speed = distance / deltaTime; // 计算速度

    qDebug() << "Mouse Speed: " << speed;

    // 更新上一次的位置和时间
    lastPos = currentPos;
    lastTime = currentTime;
}

In this example, we use static variables to keep track of the previous position and time. During each mouse movement event, we calculate the difference between the current time and the previous time, as well as the distance between the current position and the previous position. We then calculate the mouse movement speed by dividing the distance by the time difference.

This speed is measured in pixels per millisecond (px/ms). You can convert or adjust it according to your needs.

bannerAds