学习QT opengl 创建一个窗口

环境

qt creator 5.6

解释

在pro文件中添加
QT += opengl
LIBS += -lopengl32 -lglu32

定义的类需继承 public QGLWidget
然后重新实现 initializeGL()、paintGL()和resizeGL()这个三个函数

glClearColor(0.0,0.0,0.0,0.0)
参数(红色值,绿色值,蓝色值,Alpha透明度)
取值0~1之间

代码

pro

#-------------------------------------------------
#
# Project created by QtCreator 2018-06-08T08:01:36
#
#-------------------------------------------------

QT       += core gui opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = myopengl
TEMPLATE = app
LIBS += -lopengl32 -lglu32


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QtOpenGL/QtOpenGL>

namespace Ui {
class Widget;
}

class Widget : public QGLWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected:
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:
    void initWidget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <GL/glu.h>

Widget::Widget(QWidget *parent) :
    QGLWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    initWidget();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initializeGL()
{
    glShadeModel( GL_SMOOTH );//启用阴影平滑
    glClearColor(0.0,0.0,0.0,0.0);//设置清除屏幕时所用的颜色
    glClearDepth(1.0);//设置深度缓存
    glEnable(GL_DEPTH_TEST);//启用深度测试
    glDepthFunc(GL_LEQUAL);//所作深度测试类型
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);//精细的透视修正
}

void Widget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//清除屏幕和深度缓存
    glLoadIdentity();//重置当前的模型观察矩阵
}

void Widget::resizeGL(int width, int height)
{
    if(height == 0)
    {
        height = 1;
    }

    glViewport(0,0,(GLint)width,(GLint)height);//重置当前的视口
    glMatrixMode(GL_PROJECTION);//选择投影矩阵
    glLoadIdentity();//重置投影矩阵
    gluPerspective(45.0,(GLfloat)width/(GLfloat)height,0.1,100.0);//建立透视投影矩阵
    glMatrixMode(GL_MODELVIEW);//选择模型观察矩阵
    glLoadIdentity();//充值模型观察矩阵
}

void Widget::initWidget()
{
    setGeometry( 200, 200, 640, 480 );//初始化窗口位置和大小
}

运行结果

这里写图片描述

文章参考:http://qiliang.net/old/nehe_qt/lesson01.html

猜你喜欢

转载自blog.csdn.net/sinat_33859977/article/details/80617811