QT用opengl绘制一个立方体
时间: 2023-07-04 09:06:20 浏览: 182
以下是使用OpenGL和Qt绘制立方体的示例代码:
```cpp
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLVertexArrayObject>
#include <QtGui/QOpenGLBuffer>
class CubeRenderer : public QOpenGLFunctions
{
public:
CubeRenderer() {}
void initialize()
{
initializeOpenGLFunctions();
m_program = new QOpenGLShaderProgram();
m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/vertex.glsl");
m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/fragment.glsl");
m_program->link();
m_vao = new QOpenGLVertexArrayObject();
m_vao->create();
m_vao->bind();
float vertices[] = {
// Front face
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
// Back face
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
// Top face
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
// Bottom face
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
// Right face
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
// Left face
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f
};
m_vbo = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
m_vbo->create();
m_vbo->bind();
m_vbo->allocate(vertices, sizeof(vertices));
m_program->enableAttributeArray(0);
m_program->setAttributeBuffer(0, GL_FLOAT, 0, 3, 3 * sizeof(float));
m_vao->release();
m_vbo->release();
glEnable(GL_DEPTH_TEST);
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_program->bind();
m_vao->bind();
glDrawArrays(GL_QUADS, 0, 24);
m_vao->release();
m_program->release();
}
private:
QOpenGLShaderProgram *m_program;
QOpenGLVertexArrayObject *m_vao;
QOpenGLBuffer *m_vbo;
};
// 在你的OpenGL窗口中的绘制函数中调用以下代码:
CubeRenderer cubeRenderer;
cubeRenderer.initialize();
cubeRenderer.render();
```
在此示例代码中,我们使用了OpenGL的立方体顶点数据和一个简单的着色器程序来绘制立方体。我们还使用了Qt的OpenGL函数、着色器程序、顶点数组对象和缓冲区对象来管理OpenGL状态。
阅读全文