QT-openGL学习-绘制平面图形

**步骤一:**pro文件中添加 LIBS += -L -llibfreeglut -lopengl32
QT-openGL学习-绘制平面图形_第1张图片
步骤二:新建一个类并继承opengl
QT-openGL学习-绘制平面图形_第2张图片
三:代码
.h文件

#ifndef MYOPENGLWIDGET_H
#define MYOPENGLWIDGET_H

#include 
#include 
#include
#include"QOpenGLFunctions"
class MyOpenGLwidget:public QOpenGLWidget,protected QOpenGLFunctions
{
    Q_OBJECT
public:
    MyOpenGLwidget(QWidget *parent=nullptr);
public:
    void initializeGL() Q_DECL_OVERRIDE;
    void paintGL() Q_DECL_OVERRIDE;
    void resizeGL(int width,int height) Q_DECL_OVERRIDE;
};

#endif // MYOPENGLWIDGET_H

cpp文件

#include "myopenglwidget.h"

MyOpenGLwidget::MyOpenGLwidget(QWidget *parent) : QOpenGLWidget(parent)
{

}

void MyOpenGLwidget::initializeGL()
{
    initializeOpenGLFunctions();
    glClearColor(0,0,0,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHTING);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    glEnable(GL_COLOR_MATERIAL);
}

void MyOpenGLwidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBegin(GL_QUADS);//四边形绘制

        glVertex3f(-50, -50, 0);

        glVertex3f( 50, -50, 0);

        glVertex3f( 50,  50, 0);

        glVertex3f( -50,  50, 0);
    glEnd();
}

void MyOpenGLwidget::resizeGL(int width, int height)
{
    glViewport(0,0,width,height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-width/2,width/2,-height/2,height/2,-1,1);
    glMatrixMode(GL_MODELVIEW);
}

你可能感兴趣的:(QT)