qtopengl绘制三维圆柱体平移
时间: 2025-06-30 07:45:18 浏览: 9
### QTopengl 绘制 3D 圆柱体并实现平移功能
以下是基于 Qt 和 OpenGL 的示例代码,展示如何绘制一个三维圆柱体,并提供基本的平移功能:
#### 示例代码
```cpp
#include <QtWidgets/QApplication>
#include <QOpenGLWidget>
#include <QMatrix4x4>
#include <QVector3D>
class CylinderGL : public QOpenGLWidget {
public:
CylinderGL(QWidget *parent = nullptr);
protected:
void initializeGL() override;
void paintGL() override;
void resizeGL(int w, int h) override;
private:
float m_translationX = 0.0f; // X轴方向上的平移量
float m_translationY = 0.0f; // Y轴方向上的平移量
};
CylinderGL::CylinderGL(QWidget *parent)
: QOpenGLWidget(parent) {}
void CylinderGL::initializeGL() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 设置背景颜色为黑色
}
void CylinderGL::paintGL() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST); // 启用深度测试
QMatrix4x4 modelViewProjectionMatrix;
modelViewProjectionMatrix.perspective(45.0f, width() / (float)height(), 0.1f, 100.0f);
modelViewProjectionMatrix.translate(m_translationX, m_translationY, -5.0f); // 应用平移变换
glBegin(GL_QUAD_STRIP); // 使用四边形带绘制圆柱侧面
const int segments = 20; // 圆周分割数
for (int i = 0; i <= segments; ++i) {
float angle = static_cast<float>(i) / segments * M_PI * 2.0f;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, -1.0f); // 下底面顶点
glVertex3f(x, y, 1.0f); // 上底面顶点
}
glEnd();
glColor3f(1.0f, 0.0f, 0.0f); // 设置红色作为下底面的颜色
glBegin(GL_POLYGON); // 绘制下底面
for (int i = 0; i <= segments; ++i) {
float angle = static_cast<float>(i) / segments * M_PI * 2.0f;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, -1.0f);
}
glEnd();
glColor3f(0.0f, 1.0f, 0.0f); // 设置绿色作为上底面的颜色
glBegin(GL_POLYGON); // 绘制上底面
for (int i = 0; i <= segments; ++i) {
float angle = static_cast<float>(i) / segments * M_PI * 2.0f;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, 1.0f);
}
glEnd();
}
void CylinderGL::resizeGL(int w, int h) {
glViewport(0, 0, w, h);
}
// 主函数部分
int main(int argc, char **argv) {
QApplication app(argc, argv);
CylinderGL widget;
widget.resize(800, 600);
widget.show();
return app.exec();
}
```
此代码展示了如何使用 `glBegin`/`glEnd` 来绘制一个简单的圆柱体[^3]。为了支持平移功能,在矩阵中应用了翻译变换。
---
### 关键技术说明
1. **圆柱体的几何结构**
- 圆柱由两个圆形端盖(顶部和底部)以及连接它们的曲面组成。
- 曲面可以通过一系列四边形条带来近似模拟[^3]。
2. **平移功能**
- 利用了 `QMatrix4x4` 提供的 `translate()` 方法来调整对象的位置。
- 用户可以根据需求动态修改 `m_translationX` 和 `m_translationY` 变量以控制物体沿 X 轴和 Y 轴的方向移动[^4]。
3. **视口设置与投影**
- 在 `resizeGL` 函数中设置了视口大小 (`glViewport`),并在 `modelViewProjectionMatrix` 中定义了一个透视投影矩阵[^5]。
---
阅读全文
相关推荐








