QTOpenGL绘制三角形

1 QT的UI上,控件拉一个QOpenGLWidget ,点击右键,升级为类,输入类名

#include <QObject>
#include <QDebug>
#include <QWidget>
#include <QPainter>
#include <QOpenGLWidget>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>

class QOpenGLP:public QOpenGLWidget,protected QOpenGLFunctions
{ 
    Q_OBJECT
public:

    explicit  QOpenGLP(QWidget *parent = nullptr);
protected:

    void paintGL() ; //渲染OpenGL场景,每当需要更新小部件时调用
    void initializeGL() ;//设置OpenGL资源和状态
    void resizeGL(int w, int h);//设置OpenGL视口,投影等



private:
    
    QOpenGLShaderProgram *program;
   

};

#endif // QOPENGLPLAY_H
#include "qopengl***.h"
  GLint VPID = -1;
QOpenGLP::QOpenGLP(QWidget *parent):QOpenGLWidget(parent)
{
   
}

void QOpenGLP::initializeGL()
{
   
    initializeOpenGLFunctions();
 
    QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
    const char *vsrc =
            "attribute vec4 vPosition;                        \n"
            "void main() {                             \n"
            "   gl_Position = vPosition;               \n"
            "}                                         \n";
    vshader->compileSourceCode(vsrc);
    
    QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
    const char *fsrc =
            "void main() {                              \n"
            "   gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0);\n"
            "}                                          \n";
    fshader->compileSourceCode(fsrc);
     
   
    m_program = new QOpenGLShaderProgram(this);
    m_program->addShader(vshader);
    m_program->addShader(fshader);
    
    m_program->link();
  
    VPID = m_program->attributeLocation("vPosition");
   

    delete vshader;
    delete fshader;
     
}

void QOpenGLP::resizeGL(int w, int h)
{
   
}

void QOpenGLP::paintGL()
{
  
 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  
     m_program->bind();
    // 顶点位置
    GLfloat vertices[] = {
        0.0f,  1.0f,
        -0.5f, -0.5f,
         0.5f, -0.5f
    };
    
   
    glVertexAttribPointer(VPID, 2, GL_FLOAT, GL_FALSE, 0, vertices);
 
    glEnableVertexAttribArray(VPID);
 
    glDrawArrays(GL_TRIANGLES, 0, 3);
 

    glDisableVertexAttribArray(VPID);
    m_program->release();
  

}

 

posted on 2022-09-16 16:57  邗影  阅读(102)  评论(0编辑  收藏  举报

导航