Qt学习笔记-Qt中OpenGL的使用

现在窗口中心即为坐标原点,X轴从左到右,Y轴从下到上,Z轴从里到外。

 

程序运行截图如下:

Qt学习笔记-Qt中OpenGL的使用_第1张图片

 

源码如下:

myglwidget.h

#ifndef MYGLWIDGET_H
#define MYGLWIDGET_H

#include 
#include 

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 

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 

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();
}

 

你可能感兴趣的:(C/C++,Qt,OpenGL)