Qt OpenGL - 用鼠标拖动旋转

Qt OpenGL - Rotating with mouse drag

我正在阅读 Qt 文档中的 Hello GL 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();
}

 void GLWidget::setXRotation(int angle)
{
   qNormalizeAngle(angle);
   if (angle != xRot) {
       xRot = angle;
       emit xRotationChanged(angle);
       updateGL();
   }
}

我能理解他们是想计算拖动过程中x/y坐标的变化

但是他们如何将其映射到旋转场景?文档缺少对正在执行的操作的解释。

此外,这些神奇的数字是怎么回事 8

emit xRotationChanged(angle) - 在 x 轴上旋转场景

8 处理您的鼠标灵敏度

OpenGL 基本上是用来画东西的铅笔。没有这样的场景。你,程序员创建了一堆变量,然后,当需要绘制一些东西时,使用这些变量在 OpenGL 的铅笔周围移动。

在您的特定情况下,有一些变量 xRotyRotzRot 用于创建应用于绘制对象的转换链。实际绘图发生在 GLWidget::paintGL;我给你注释了:

 void GLWidget::paintGL()
 {
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glLoadIdentity(); // reset transformation state
     glTranslatef(0.0, 0.0, -10.0); // apply translation to transformation
     glRotatef(xRot / 16.0, 1.0, 0.0, 0.0); // apply rotation on x
     glRotatef(yRot / 16.0, 0.0, 1.0, 0.0); // apply rotation on x
     glRotatef(zRot / 16.0, 0.0, 0.0, 1.0); // apply rotation on x
     logo->draw(); // draw logo using the currently set transformation
 }