Search code examples
c++openglqt5opengl-extensionsqopenglfunctions

How to use extension like glGenBuffersARB in Qt5?


I am trying desperately to understand the architecture of OpenGL support in Qt5.

My current problem is this: I have some existing OpenGL code (desktop, not OpenGL ES) that uses some OpenGL extensions, including glGenBuffersARB. Outside Qt5 getting access to the functions for extensions like this is trivial, for example by using GLEW I could simply do this:

glewInit();

And everything would just magically work as expected, and I could start to use glGenBuffersARB straight away. If I was ever worried, I could throw in a call to glewIsSupported to be sure it was supported.

But in Qt5 there is a warning that GLEW and QOpenGLFunctions don't play well together (copied from qopenglfunctions.h):

#ifdef __GLEW_H__
#if defined(Q_CC_GNU)
#warning qopenglfunctions.h is not compatible with GLEW, GLEW defines will be undefined
#warning To use GLEW with Qt, do not include <qopengl.h> or <QOpenGLFunctions> after glew.h
#endif
#endif

So let's say that I for the sake of this question and to satisfy the curiosity ditch GLEW completely and rely solely on Qt5 for a pure Qt5 approach. How would I get my existing OpenGL code that relies on glGenBuffersARB to work without manually binding each and every extension function manually?

NOTE: I know I can follow tips in this answer and do this:

auto functions = context->versionFunctions<QOpenGLFunctions_3_3_Core>();
if (!functions) error();
functions->initializeOpenGLFunctions();
functions->glGenBuffersARB(...);

But then I would have to prefix every single line of existing OpenGL code with functions-> which I would rather not do.


Solution

  • The way to have GL functions be available to the class in Qt5, without needing to use a helper, is to make your GL class derive from a subclass of QAbstractOpenGLFunctions. For example your header file might look something like this:

    #include <QOpenGLFunctions_1_1>
    class MyGLClass : protected QOpenGLFunctions_1_1
    {
        ...
    }
    

    Then in your initialize method you need to initialize the OpenGL functions like so:

    void MyGLClass::initialize()
    {
        if (!initializeOpenGLFunctions()) {
            qFatal("initializeOpenGLFunctions failed");
        }
    }