Qt Mouse Movement Direction Detection

In Qt, you can obtain the direction of mouse movement by overriding the mouseMoveEvent function of QWidget. Below are the specific steps:

  1. event that occurs when the mouse is moved
void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
    QPoint currentPosition = event->pos();
    QPoint previousPosition = event->oldPos();

    // 计算鼠标移动的方向
    int deltaX = currentPosition.x() - previousPosition.x();
    int deltaY = currentPosition.y() - previousPosition.y();

    if (deltaX > 0) {
        // 鼠标向右移动
    } else if (deltaX < 0) {
        // 鼠标向左移动
    }

    if (deltaY > 0) {
        // 鼠标向下移动
    } else if (deltaY < 0) {
        // 鼠标向上移动
    }

    // 其他处理逻辑
    // ...

    // 调用父类的mouseMoveEvent函数
    QWidget::mouseMoveEvent(event);
}
  1. In the rewritten mouseMoveEvent function, you can use event->pos() to retrieve the current mouse position and event->oldPos() to retrieve the previous mouse position. Then, you can calculate the horizontal and vertical displacement of the mouse movement, denoted as deltaX and deltaY.
  2. The direction of mouse movement can be determined by the values of deltaX and deltaY. For example, when deltaX is greater than 0, it indicates that the mouse is moving right; when deltaX is less than 0, it indicates that the mouse is moving left; when deltaY is greater than 0, it indicates that the mouse is moving down; when deltaY is less than 0, it indicates that the mouse is moving up.
  3. After determining the direction in which the mouse is moving, additional processing logic can be performed as needed.
  4. Finally, remember to call QWidget::mouseMoveEvent(event) at the end of the function to ensure that the event continues to be passed to the parent class for handling.
bannerAds