Rotating the scene in OpenGL using the mouse (Qt)
To study the material of the article "Rotating a Scene in OpenGL Using the Mouse", you first need to study the material of this article.
The idea is very simple - intercept the mouse event, determine the mouse pointer movement speed, and based on this, calculate the scene rotation angle. Essentially the same as in the previous example, but the rotation is not done by a timer, but by a mouse event (mouse movement with a pressed button).
void WOpengl::rotate()
{
//Check for overflow (360 degrees)
(angle_x > 360)? angle_x = 0 : 0;
(angle_z > 360)? angle_z = 0 : 0; //Check for overflow (0 degrees)
(angle_x < 0)? angle_x = 360: 0;
(angle_z < 0)? angle_z = 360: 0;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotate the system
glRotated(angle_x,1,0,0);
glRotated(angle_z,0,1,0);
//Call the drawing function
paintGL();
}
void WOpengl::mouseMoveEvent(QMouseEvent*me)
{
//Check for significant deviation - for example, to prevent the scene from rotating when minimizing and maximizing the window, when moving the cursor over a large distance with release, etc. Not necessary, but more natural
if(abs(me->x()-mouse_x)>=20)
mouse_x=me->x();
if(abs(me->y()-mouse_y)>=20)
mouse_y=me->y();
//Change the rotation angle depending on the mouse position
angle_x += (mouse_y-me->y())/2;
angle_z += (mouse_x-me->x())/2;
//Save the current cursor coordinates for the ability to determine their speed of change
mouse_x = me->x();
mouse_y = me->y();
//Call the method that will handle the rotation and display the updated image
rotate();
It is clear that all new methods and variables need to be defined:
class WOpengl: public QGLWidget
{
Q_OBJECT
public:
...
double angle_x;
double angle_z;
double mouse_x;
double mouse_y;
void mouseMoveEvent(QMouseEvent *me);
...
}
That's all.Ready project: qtopengl_rotate