原文:http://www.trentreed.net/blog/qt5-opengl-part-0-creating-a-window/
Qt5中增加了QOpenGL*类,这代替了QGL*类,Qt5OpenGL模块中QGL*类依然可用,但推荐使用新的QOpenGL*类。
在本课程中将使用QOpenGLWindow类,此类继承自Qt5Gui类,因此我们可以使用它而不必使用Qt5Widgets模块,functions->glFunctionHere();
window.h
#ifndef WINDOW_H
#define WINDOW_H
#include
#include
class Window: public QOpenGLWindow,
protected QOpenGLFunctions
{
Q_OBJECT
public:
~Window();
void initializeGL();
void resizeGL(int width, int height);
void paintGL();
void teardownGL();
private:
void printContextInformation();
};
#endif
#include "window.h"
#include
#include
Window::~Window()
{
makeCurrent();
teardownGL();
}
void Window::initializeGL()
{
// 初始化 OpenGL 后端
initializeOpenGLFunctions();
printContextInformation();
glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
}
void Window::resizeGL(int width, int height)
{
// 未做处理
}
void Window::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
}
// 回收资源
void Window::teardownGL()
{
}
// 打印相关信息,调试用
void Window::printContextInformation()
{
QString glType;
QString glVersion;
QString glProfile;
// 获取版本信息
glType = (context()->isOpenGLES()) ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast(glGetString(GL_VERSION));
// 获取 Profile 信息
#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
switch (format().profile())
{
CASE(NoProfile);
CASE(CoreProfile);
CASE(CompatibilityProfile);
}
#undef CASE
qDebug() << qPrintable(glType) << qPrintable(glVersion) << "(" << qPrintable(glProfile) << ")";
}
/*
void MyGlWidget::keyPressEvent(QKeyEvent *e)
{
switch(e->key())
{
case Qt::Key_F2:
fullscreen = !fullscreen;
if (fullscreen)
{
showFullScreen();
}
else
{
showNormal();
setGeometry(100, 100, 640, 480);
}
updateGL();
break;
case Qt::Key_Escape:
close();
}
}
*/
#include
#include "window.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
// 设置 OpenGL 信息
// 注意:必须在show()之前设置信息
QSurfaceFormat format;
format.setRenderableType(QSurfaceFormat::OpenGL);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setVersion(3,3);
Window window;
window.setFormat(format);
window.resize(QSize(800, 600));
window.show();
return app.exec();
}