如何在Qt QOpenGLWidget中启用正交投影?
时间: 2024-11-03 10:17:07 浏览: 49
在Qt的QOpenGLWidget中启用正交投影,你需要设置视口的投影模式为`QOpenGLFunctions::Projection::Orthographic`。这通常通过以下步骤完成:
1. 首先,确保你的QOpenGLContext或QOpenGLWidget已经连接到一个支持OpenGL的渲染上下文。
```cpp
QOpenGLContext* context = new QOpenGLContext();
context->makeCurrent(your_widget); // your_widget是你创建的QOpenGLWidget实例
```
2. 创建一个QOpenGLFunctions对象,以便访问OpenGL函数,如setViewport()和gluOrtho2D()。
```cpp
QOpenGLFunctions *functions = your_widget->functions();
```
3. 设置视口大小,并切换到正交投影模式。假设你想要一个从左到右、从底到顶的视口,宽度和高度分别为width和height。
```cpp
// 先清空当前矩阵
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// 设置正交投影
float left = -0.5f * width; // 左边界
float right = 0.5f * width; // 右边界
float bottom = -0.5f * height; // 底部边界
float top = 0.5f * height; // 顶部边界
float near_val = 0.1f; // 近裁剪面
float far_val = 100.0f; // 远裁剪面
functions->gluOrtho2D(left, right, bottom, top);
```
4. 你可以选择是否需要更新视口(viewport),有时候这一步会被省略,取决于你在何时切换到正交投影模式。
```cpp
your_widget->updateGL(); // 如果需要更新视口
```
阅读全文
相关推荐















