您的位置:首页 > 编程语言 > Qt开发

QT中使用OpenGL(0)——创建一个窗口

2016-04-10 18:41 1421 查看
原文: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


window.cpp

#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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: