QOpenGLShaderProgram 空心矩形, 完善代码列子
时间: 2023-05-23 14:02:06 浏览: 195
以下是完整的代码示例:
```
#include <QApplication>
#include <QOpenGLWidget>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
class GLWidget : public QOpenGLWidget
{
public:
GLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent), m_program(this)
{}
protected:
void initializeGL() override
{
// Initialize the OpenGL function pointers.
initializeOpenGLFunctions();
// Compile the vertex shader.
m_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
"#version 330\n"
"in vec2 position;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(position, 0.0, 1.0);\n"
"}\n");
// Compile the fragment shader.
m_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
"#version 330\n"
"uniform vec4 color;\n"
"out vec4 fragmentColor;\n"
"void main()\n"
"{\n"
" fragmentColor = color;\n"
"}\n");
// Link the program.
m_program.link();
// Create a vertex array object.
m_vao.create();
QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
// Create a vertex buffer.
m_vbo.create();
m_vbo.bind();
float vertices[] = {
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f
};
m_vbo.allocate(vertices, sizeof(vertices));
m_program.setAttributeBuffer("position", GL_FLOAT, 0, 2);
m_program.enableAttributeArray("position");
// Set the clear color.
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
}
void paintGL() override
{
// Clear the framebuffer.
glClear(GL_COLOR_BUFFER_BIT);
// Bind the vertex array object and the shader program.
QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
m_program.bind();
// Draw a hollow rectangle.
m_program.setUniformValue("color", QColor(Qt::white));
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_QUADS, 0, 4);
// Swap the buffers.
swapBuffers();
}
private:
QOpenGLShaderProgram m_program;
QOpenGLVertexArrayObject m_vao;
QOpenGLBuffer m_vbo;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
GLWidget widget;
widget.show();
return app.exec();
}
```
此代码将创建一个空心矩形并使用OpenGL着色器绘制它。可以在 `initializeGL` 和 `paintGL` 函数中看到着色器的编写和如何将形状添加到顶点缓冲区中进行渲染。在 `paintGL` 函数中,`glPolygonMode` 函数被用于将渲染方式从填充到线框切换。
阅读全文