Qt Opengl画一个渐变三角形,不要使用着色器,输出完整代码
时间: 2024-03-05 11:54:25 浏览: 43
好的,下面是完整的Qt Opengl代码示例:
```
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLTexture>
class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
public:
GLWidget(QWidget *parent = nullptr)
: QOpenGLWidget(parent)
{
}
protected:
void initializeGL() override
{
initializeOpenGLFunctions();
// 创建顶点和颜色数组
GLfloat vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
GLfloat colors[] = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
// 创建纹理并加载渐变颜色图像
QImage image(256, 1, QImage::Format_RGB888);
for (int i = 0; i < 256; i++) {
image.setPixelColor(i, 0, QColor(i, i, i));
}
m_texture = new QOpenGLTexture(image);
// 绑定纹理并设置过滤器和纹理坐标
m_texture->bind();
m_texture->setMinificationFilter(QOpenGLTexture::Nearest);
m_texture->setMagnificationFilter(QOpenGLTexture::Linear);
m_texture->setWrapMode(QOpenGLTexture::Repeat);
// 启用顶点和颜色数组并设置顶点和颜色数据
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
// 绘制三角形并关闭顶点和颜色数组
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
}
void resizeGL(int w, int h) override
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void paintGL() override
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
}
private:
QOpenGLTexture* m_texture;
};
```
这个示例可以在Qt中创建一个OpenGL窗口,并在窗口中绘制一个渐变三角形,而无需使用着色器。