QOpenGLShaderProgram 空心矩形, 背景透明, 完善代码列子
时间: 2023-05-21 20:04:14 浏览: 122
很高兴为您解答这个问题。以下是创建具有空心矩形和透明背景的 QOpenGLShaderProgram 的完整代码示例:
```
#include <QCoreApplication>
#include <QSurfaceFormat>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLWidget>
class QTransparentRectangleWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
public:
void initializeGL()
{
// 设置 OpenGL 的清除颜色为全透明
glClearColor(0, 0, 0, 0);
// 初始化 OpenGL 函数
initializeOpenGLFunctions();
// 加载顶点和片段着色器
m_program.addShaderFromSourceCode(QOpenGLShader::Vertex, "#version 330\n"
"layout (location = 0) in vec2 position;\n"
"uniform mat4 projectionMatrix;\n"
"void main()\n"
"{\n"
" gl_Position = projectionMatrix * vec4(position, 0.0, 1.0);\n"
"}\n");
m_program.addShaderFromSourceCode(QOpenGLShader::Fragment, "#version 330\n"
"out vec4 FragColor;\n"
"uniform vec4 color;\n"
"void main()\n"
"{\n"
" FragColor = color;\n"
"}\n");
// 绑定属性
m_program.bindAttributeLocation("position", 0);
// 编译和链接着色器程序
bool programLinked = m_program.link();
Q_ASSERT(programLinked);
(void)programLinked;
// 生成和绑定一个顶点缓冲区对象
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
// 设定顶点属性
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
}
void resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
m_projectionMatrix.setToIdentity();
m_projectionMatrix.ortho(0, w, h, 0, -1, 1);
}
void paintGL()
{
// 清除颜色缓存
glClear(GL_COLOR_BUFFER_BIT);
// 使用着色器程序
m_program.bind();
// 传递 Uniform 值
m_program.setUniformValue("projectionMatrix", m_projectionMatrix);
m_program.setUniformValue("color", QColor(255, 0, 0, 127));
// 画一个空心矩形
const GLfloat vertices[] = {
50.0f, 50.0f,
200.0f, 50.0f,
200.0f, 200.0f,
50.0f, 200.0f,
50.0f, 50.0f
};
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glDrawArrays(GL_LINE_STRIP, 0, 5);
}
private:
QOpenGLShaderProgram m_program;
GLuint m_vbo;
QMatrix4x4 m_projectionMatrix;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QSurfaceFormat format;
format.setDepthBufferSize(24);
QSurfaceFormat::setDefaultFormat(format);
QApplication a(argc, argv);
QTransparentRectangleWidget widget;
widget.resize(400, 400);
widget.show();
return a.exec();
}
```
希望这个代码示例对您有所帮助!
阅读全文