1. 程式人生 > >Qt學習筆記-Qt中OpenGL的使用

Qt學習筆記-Qt中OpenGL的使用

現在視窗中心即為座標原點,X軸從左到右,Y軸從下到上,Z軸從裡到外。

程式執行截圖如下:

原始碼如下:

myglwidget.h

#ifndef MYGLWIDGET_H
#define MYGLWIDGET_H

#include <QWidget>
#include <QGLWidget>

class MyGLWidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit MyGLWidget(QWidget *parent = 0);

signals:

protected:
    void initializeGL();
    void resizeGL(int w, int h);
    void paintGL();

public slots:
};

#endif // MYGLWIDGET_H

main.cpp

#include "myglwidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MyGLWidget w;
    w.resize(400,300);
    w.show();

    return a.exec();
}

myglwidget.cpp

#include "myglwidget.h"
#include <GL/glu.h>

MyGLWidget::MyGLWidget(QWidget *parent) : QGLWidget(parent)
{

}

void MyGLWidget::initializeGL()
{
    glClearColor(0.0,0.0,0.0,0.0);
    glShadeModel(GL_SMOOTH);
    glClearDepth(1.0);
    glEnable(GL_DEPTH_TEST);
}

void MyGLWidget::resizeGL(int w, int h)
{
    glViewport(0,0,(GLint)w,(GLint)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0,(GLfloat)w/(GLfloat)h,0.1,100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void MyGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glTranslatef(-2.0,0.0,-6.0);
    glBegin(GL_TRIANGLES);
    glVertex3f(-1.0,1.0,0.0);
    glVertex3f(0.0,-1.0,0.0);
    glVertex3f(1.0,1.0,0.0);
    glEnd();

    glTranslatef(4.0,0.0,0.0);
    glBegin(GL_QUADS);
    glVertex3f(-1.0,1.0,0.0);
    glVertex3f(-1.0,-1.0,0.0);
    glVertex3f(1.0,-1.0,0.0);
    glVertex3f(1.0,1.0,0.0);
    glEnd();
}