Qt提供了两种可以使用opengl渲染的qwidget派生类,一是QGLWidget,二是QOpenGLWidget。但是前者逐渐不被采用。此外,opengl也逐渐放弃旧的 glBegin() - glEnd()模式,而是采用glDrawArrays()。本篇博文演示利用QOpenGLWidget和glDrawArrays结合,实现纹理贴图。
头文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
Q_OBJECT
public:
GLWidget(QWidget *parent = 0);
~GLWidget();
GLuint m_id;
unsigned char m_arrData[1024];
protected:
void initializeGL() Q_DECL_OVERRIDE;
void paintGL() Q_DECL_OVERRIDE;
void resizeGL(int width, int height) Q_DECL_OVERRIDE;
void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
//void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
//void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
};
#endif // MAINWINDOW_H
cpp文件:
#include "glwidget.h"
#include <QImage>
#include "math3d.h"
GLWidget::GLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
int iVal = 0;
for(int iIndex = 0;iIndex < 4; iIndex++)
{
if(0 == iVal)
{
iVal = 255;
}
else
{
iVal = 0;
}
memset(m_arrData + 32 * 8 * iIndex, iVal, 32 * 8);
}
}
GLWidget::~GLWidget()
{
glDeleteTextures(1, &m_id);
}
void GLWidget::initializeGL()
{
initializeOpenGLFunctions();//这句必须有,否则程序会崩溃
glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_2D, m_id);
//这下面的两句是必要的,否则在绘制区的像素数和纹理的像素数不等时,图案不能正常显示
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 32, 32, 0, GL_LUMINANCE,//GL_INTENSITY,
GL_UNSIGNED_BYTE, m_arrData);
}
void GLWidget::paintGL()
{
M3DVector2f arrVetex[4] = {{0.0,0.0}, {100.0, 0.0}, {100.0, 100.0}, {0.0, 100.0}};//M3DVector2f是math3d.h定义的类型
float arrTex[8] = {0.0,0.0,1.0, 0.0,1.0, 1.0, 0.0, 1.0};
glBindTexture(GL_TEXTURE_2D, m_id);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, arrTex);
glVertexPointer(2, GL_FLOAT, 0, &arrVetex[0]);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
void GLWidget::resizeGL(int width, int height)
{
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 100.0, 0.0, 100.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
//m_iTick++;
update();
}
结果: