// glwidget.h
#ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QtCore>
#include <QtGui>
#include <QtOpenGL>
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLWidget(int timerInterval = 0, QWidget *parent = 0);
protected:
virtual void initializeGL() = 0;
virtual void resizeGL(int width, int height) = 0;
virtual void paintGL() = 0;
virtual void keyPressEvent(QKeyEvent *e);
virtual void timeOut();
protected slots:
virtual void timeOutSlot();
private:
QTimer *m_timer;
};
#endif
// glwidget.cpp
#include "glwidget.h"
GLWidget::GLWidget(int timerInterval, QWidget *parent)
: QGLWidget(parent)
{
if (timerInterval == 0) {
m_timer = 0;
} else {
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timeOutSlot()));
m_timer->start(timerInterval);
}
}
void GLWidget::keyPressEvent(QKeyEvent *e)
{
switch (e->key()) {
case Qt::Key_Escape:
close();
}
}
void GLWidget::timeOut()
{
}
void GLWidget::timeOutSlot()
{
timeOut();
}
// glwidget2.h
#ifndef GLWIDGET2_H
#define GLWIDGET2_H
#include "../glwidget.h"
class GLWidget2 : public GLWidget
{
// Q_OBJECT //! 注意:此处不能有Q_OBJECT
public:
GLWidget2(int timerInterval = 0, QWidget *parent = 0);
protected:
virtual void initializeGL();
virtual void resizeGL( int width, int height );
virtual void paintGL();
};
#endif // GLWIDGET2_H
// glwidget2.cpp
#include "glwidget2.h"
GLWidget2::GLWidget2(int timerInterval, QWidget *parent)
: GLWidget(timerInterval, parent)
{
}
void GLWidget2::initializeGL()
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void GLWidget2::resizeGL(int width, int height)
{
height = height?height:1;
glViewport( 0, 0, (GLint)width, (GLint)height );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void GLWidget2::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清除屏幕和深度缓存
glLoadIdentity(); // 重置当前的模型观察矩阵
glTranslatef(-1.5f,0.0f,-6.0f); // 相对当前所在的屏幕位置移动
glBegin(GL_TRIANGLES); // 开始绘制三角形
glVertex3f( 0.0f, 1.0f, 0.0f); // 上顶点
glVertex3f(-1.0f,-1.0f, 0.0f); // 左下顶点
glVertex3f( 1.0f,-1.0f, 0.0f); // 右下顶点
glEnd(); // 三角形绘制结束
/* 使用顺时针次序画正方形(左上->右上->右下->左下), 采用顺时针绘制的
是对象的后表面.
*/
glTranslatef(3.0f,0.0f,0.0f); // 向x轴正方向移动3个单位
glBegin(GL_QUADS); // 开始绘制四边形
glVertex3f(-1.0f, 1.0f, 0.0f); // 左上顶点
glVertex3f( 1.0f, 1.0f, 0.0f); // 右上顶点
glVertex3f( 1.0f,-1.0f, 0.0f); // 右下顶点
glVertex3f(-1.0f,-1.0f, 0.0f); // 左下顶点
glEnd(); // 四边形绘制结束
}
// main.cpp
#include "glwidget2.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GLWidget *w = new GLWidget2;
w->show();
return a.exec();
}