天天看點

學習QT opengl 多邊形環境解釋代碼運作結果

  • 環境
  • 解釋
  • 代碼
  • 運作結果

環境

qt creator 5.6

解釋

glTranslatef(x, y, z)沿着 X,、Y 、 Z 軸移動。

x左右移動。左負,右正

y上下移動。上正,下負

z前後移動。前正,後負

代碼

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 = );
    ~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(,,,);//設定清除螢幕時所用的顔色
    glClearDepth();//設定深度緩存
    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();//重置目前的模型觀察矩陣

    glTranslatef( -,  , - );//glTranslatef(x, y, z)沿着 X, Y 和 Z 軸移動
    glBegin(GL_TRIANGLES);//開始繪制三角形
    glVertex3f(,,);//上頂點
    glVertex3f(-,-,);//左下頂點
    glVertex3f(,-,);//右下頂點
    glEnd();//三角形繪制結束

    glTranslatef(,,);//向右移動三個機關,在螢幕右邊繪制正方形
    glBegin(GL_QUADS);//開始繪制四邊形
    glVertex3f(-,,);//左上頂點
    glVertex3f(,,);//右上頂點
    glVertex3f(,-,);//右下頂點
    glVertex3f(-,-,);//左下頂點
    glEnd();//四邊形繪制結束

}

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

    glViewport(,,(GLint)width,(GLint)height);//重置目前的視口
    glMatrixMode(GL_PROJECTION);//選擇投影矩陣
    glLoadIdentity();//重置投影矩陣
    gluPerspective(,(GLfloat)width/(GLfloat)height,,);//建立透視投影矩陣
    glMatrixMode(GL_MODELVIEW);//選擇模型觀察矩陣
    glLoadIdentity();//充值模型觀察矩陣
}

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

           

運作結果

學習QT opengl 多邊形環境解釋代碼運作結果

文章參考:http://qiliang.net/old/nehe_qt/lesson02.html

繼續閱讀