Qt下使用OpenGL(1)-根据NeHe的教程改写的

来源:互联网 发布:ipad免越狱下载软件 编辑:程序博客网 时间:2024/04/28 19:58


下面这个网址上有前辈们已经实现的一部分,但发现有些地方对Qt5以上版本的不适用,故做了些修改……有兴趣的可以先看看前辈实现的这个:

http://www.qiliang.net/old/nehe_qt/

还有这个前辈写的也不错:http://blog.csdn.net/fuyajun01/article/category/871042

话不多说,直接上代码了……

忘了说了,编译环境:win 7 32 bit, Qt 5.1.1, vs 2010

第一课:创建OpenGL窗口

 nehewidget.h 头文件:

 

#ifndef NEHEWIDGET_H#define NEHEWIDGET_H#include <QtOpenGL/QGLWidget>//#include "ui_nehewidget.h"#include <qgl.h>class nehewidget : public QGLWidget{Q_OBJECTpublic:nehewidget(QWidget *parent = 0,bool fs=false);~nehewidget();protected:void initializeGL();void paintGL();void resizeGL(int w,int h);void keyPressEvent(QKeyEvent *e);bool fullscreen;};#endif // NEHEWIDGET_H

 

nehewidget.cpp 实现文件:

 

#include "nehewidget.h"#include <gl/GLU.h>#include <QKeyEvent>nehewidget::nehewidget(QWidget *parent,bool fs): QGLWidget(parent){fullscreen=fs;setGeometry(0,0,640,480);//setCaption("OpenGL window"); //这个函数,不支持了吧?setWindowTitle("OpenGL Window");if(fullscreen) showFullScreen();}nehewidget::~nehewidget(){}void nehewidget::initializeGL(){glShadeModel(GL_SMOOTH);glClearColor(0,0,0,0);glClearDepth(1.0);glEnable(GL_DEPTH_TEST);glDepthFunc(GL_LEQUAL);glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);}void nehewidget::paintGL(){glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);glLoadIdentity();}void nehewidget::resizeGL(int w,int h){if(h==0) h=1;glViewport(0,0,(GLint)w,(GLint)h);glMatrixMode(GL_PROJECTION);glLoadIdentity();//下面这个函数在Qt和OpenGL新版本中都不支持了!先注释掉吧,以后不得不用时再想办法//gluPerspective(45.0,(GLfloat)w/(GLfloat)h,0.1,100.0);glMatrixMode(GL_MODELVIEW);glLoadIdentity();}void nehewidget::keyPressEvent(QKeyEvent *e){switch(e->key()) {case Qt::Key_F2:fullscreen=!fullscreen;if(fullscreen) showFullScreen();else {showNormal();setGeometry(0,0,640,480);}updateGL();break;case Qt::Key_Escape:close();}}

 

main 主函数:

#include "nehewidget.h"#include <QtWidgets/QApplication>#include <QMessageBox>int main(int argc, char *argv[]){bool fs=false;QApplication a(argc, argv);switch(QMessageBox::information(0,"FullScreen?","Fullscreen or not?",QMessageBox::Yes,QMessageBox::No|QMessageBox::Default)) {case QMessageBox::Yes:fs=true;break;case QMessageBox::No:fs=false;break;}nehewidget w(0,fs);w.show();return a.exec();}

 

0 0
原创粉丝点击