原文:http://www.trentreed.net/blog/qt5-opengl-part-0-creating-a-window/
Qt5中增加了QOpenGL*类,这代替了QGL*类,Qt5OpenGL模块中QGL*类依然可用,但推荐使用新的QOpenGL*类。
在本课程中将使用QOpenGLWindow类,此类继承自Qt5Gui类,因此我们可以使用它而不必使用Qt5Widgets模块,这与QGL*与Qt Widgets高度耦合是完全不同的。
QOpenGLWindow类有以下功能:
initializeGL()
resizeGL(int width, int height)
paintGL()
在这些函数中可以完成我们的逻辑。
为方面使用OpenGL函数,从QOpenGLWindow继承的同时又同时从QOpenGLFunctions继承,当前QT版本中,不需
要GLEW,因为QOpenGLFunctions可以访问OpenGL ES 2.0 API。也可以不从QOpenGLFunctions继承,通过 QOpenGLContext
来访问OpenGL函数,用法有2种
QOpenGLFunctions functions(QOpenGLContext::currentContext());
functions.glFunctionHere();
// 或者
QOpenGLFunctions *functions = QOpenGLContext::currentContext()->functions();
functions->glFunctionHere();
window.h
#ifndef WINDOW_H
#define WINDOW_H
#include <QOpenGLWindow>
#include <QOpenGLFunctions>
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 <QDebug>
#include <QString>
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<const char*>(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();
}
}
*/
main.cpp
#include <QApplication>
#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();
}
本文介绍如何使用Qt5中的QOpenGLWindow类创建OpenGL窗口,并详细解释了initializeGL、resizeGL和paintGL等关键函数的使用方法。
——创建一个窗口&spm=1001.2101.3001.5002&articleId=51114262&d=1&t=3&u=ea9601fc25954a88a8bc04eca42a5161)
4536

被折叠的 条评论
为什么被折叠?



