2

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)

Andon M. Coleman
  • 42,359
  • 2
  • 81
  • 106
Jay
  • 13,803
  • 4
  • 42
  • 69

2 Answers2

3

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).

peppe
  • 21,934
  • 4
  • 55
  • 70
1

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.

Andon M. Coleman
  • 42,359
  • 2
  • 81
  • 106
  • A great help. I wondered about it but didn't know OpenGl well enough to know if it would work – Jay Sep 13 '13 at 01:27
  • "WGL has a strict one-to-one mapping for contexts and threads" that's actually true in all GL implementations. The only problem is that the current context might not be your `QOpenGLContext`, that's why I didn't suggest this way... – peppe Sep 13 '13 at 07:13
  • @peppe: Indeed, that is why I mentioned having to do this from the window's draw event handler. I mentioned WGL by name because this question is about WGL, it is definitely true that all existing window system implementations have this issue. – Andon M. Coleman Sep 13 '13 at 07:25
  • This seems less version dependent than peppe's solution. If I can ensure I call it in the correct event. Perhaps QQuickItem::updatePaintNode(). I'll keep after it. Thank you again – Jay Sep 13 '13 at 14:37