Get OpenGL (WGL) context from QOpenGLContext

2.9k Views Asked by At

I'm trying to get the OpenGL context (HGLRC) from the QQuickView window. I need to pass it to a non-Qt library. I can get a QOpenGLContext easily enough:

m_qtContext = QOpenGLContext::currentContext();

How do you obtain the OpenGL context from the Qt class? (QOpenGLContext)

2

There are 2 best solutions below

4
On

You can get the current OpenGL context from WGL in any framework if you call wglGetCurrentContext (...) while your thread has the context bound. Keep in mind that frameworks will usually change the current context whenever they invoke a window's draw callback / event handler, and may even set it to NULL after completing the callback.

WGL has a strict one-to-one mapping for contexts and threads, so in a single-threaded application that renders to multiple windows you will probably have to call this function in a window's draw callback / event handler to get the proper handle.

In simplest terms, any time you have a valid context in which to issue GL commands under Win32, you can get a handle to that particular context by calling wglGetCurrentContext (...).


If your framework has a portable way of acquiring a native handle, then by all means use it. But that is definitely not your only option on Microsoft Windows.

0
On

There's not exactly a public API for this, as far as I know. Note that Qt 5 removed most of the native handles from the APIs. This should do the trick:

QPlatformNativeInterface *iface = QGuiApplication::platformNativeInterface();
HGLRC ctx = (HGLRC)iface->nativeResourceForContext("renderingContext", context);

(not sure about the last cast, but that looks correct according to the relevant source).