I have a GLWdiget subclass of QGLWidget where I would like to make rotate a 3D object along Ox and Oy axes.
For this, I have reimplemented mousePressEvent
and mouseMoveEvent
functions this way :
void GLWidget::mousePressEvent(QMouseEvent *event)
{
lastPos = event->pos();
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
float dx = (event->x() - lastPos.x()) / 10.0f;
float dy = (event->y() - lastPos.y())/ 10.0f;
if (event->buttons() & Qt::LeftButton)
{
glRotatef(dy*0.1, 1.0f, 0.0f, 0.0f);
glRotatef(dx*0.1, 0.0f, 1.0f, 0.0f);
}
}
My problem is that dx
and dy
are never negative so whatever the direction I do with the mouse, it is always rotating in the same direction.
For example, If I drag horizontally to the right, I want the object to rotate along 0y axes with a positive angle, and If I drag horizontally to the left, with a negative angle.
This would be the same for vertical dragging but the rotation would be along Ox axes.
Is this issue coming from global coordinates ? However, event->x
and event->y
give positions relative to the GLWidget.
You are not updating the lastPos at the end of your mouseMoveEvent ? From the Qt example:
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
int dx = event->x() - lastPos.x();
int dy = event->y() - lastPos.y();
if (event->buttons() & Qt::LeftButton) {
setXRotation(xRot + 8 * dy);
setYRotation(yRot + 8 * dx);
} else if (event->buttons() & Qt::RightButton) {
setXRotation(xRot + 8 * dy);
setZRotation(zRot + 8 * dx);
}
lastPos = event->pos();
}
I suggest you take a look at Qt Hello GL which seems to match your use case.