[SOLVED] Qt keeping mouse centered

Issue

I’m wondering if anyone has a trick to keep the mouse position centered in a (QGL)widget for Qt. I read that one could set the mouseposition after finding the delta, but this way works very buggy for me. Mouse events are not properly registered, any if they do, very jumpy.

void World::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {

        GLfloat dx = GLfloat(event->x() - lastPos.x()) / width();
        GLfloat dy = GLfloat(event->y() - lastPos.y()) / height();

        player->rotHorizontal += 360.0 * dx;
        if(player->rotHorizontal < 0.0)
            player->rotHorizontal += 360.0;
        else if(player->rotHorizontal > +360.0)
            player->rotHorizontal -= 360.0;

        player->rotVertical += 360.0 * dy;

        if (player->rotVertical > MAX_ROTATION_UP) {
            player->rotVertical = MAX_ROTATION_UP;
        } else if (player->rotVertical < -MAX_ROTATION_UP) {
            player->rotVertical = -MAX_ROTATION_UP;
        }

    }
//    int diffX = event->pos().x() - lastPos.x() % 20;
//    int diffY = event->pos().y() - lastPos.y() % 20;
//    if (diffY > 10 || diffX > 10 || diffY < -10 || diffX < -10) {
//        QPoint glob = mapToGlobal(QPoint(this->pos().x() + width()/2, this->pos().y() + height()/2));
//        QCursor::setPos(glob);
//    }
    lastPos = event->pos();
    QGLWidget::mouseMoveEvent(event);
}

I commented out the code which would keep the mouse centered. If this would work, I would place it in the leftclick area.

Solution

Fixed:

void World::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {

        GLfloat dx = GLfloat(event->x() - lastPos.x()) / width();
        GLfloat dy = GLfloat(event->y() - lastPos.y()) / height();

        player->rotHorizontal += 360.0 * dx;
        if(player->rotHorizontal < 0.0)
            player->rotHorizontal += 360.0;
        else if(player->rotHorizontal > +360.0)
            player->rotHorizontal -= 360.0;

        player->rotVertical += 360.0 * dy;

        if (player->rotVertical > MAX_ROTATION_UP) {
            player->rotVertical = MAX_ROTATION_UP;
        } else if (player->rotVertical < -MAX_ROTATION_UP) {
            player->rotVertical = -MAX_ROTATION_UP;
        }

    }
    QPoint glob = mapToGlobal(QPoint(width()/2,height()/2));
    QCursor::setPos(glob);
    lastPos = QPoint(width()/2,height()/2);
    QGLWidget::mouseMoveEvent(event);
}

Answered By – RobotRock

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *