2

I wish to use OpenGL to render to an offscreen buffer in a separate thread. I don't need the context to be shared with the main thread. Previously, I used the QOpenGLContext class in Qt 5.4, which I initialised in the main thread, then moved to the worker thread using its moveToThread and makeCurrent methods. This worked fine for my needs, but now I have to backport it to Qt 4.8 . I tried just initialising a QGLContext on my own, but when I call create on it, that just returns false and I can't understand what my error is. What is the proper way to do this in Qt 4.8 ?

Moshev
  • 556
  • 6
  • 14

1 Answers1

2

In Qt 4, the context should always remain in the GUI thread. But with Qt 4.8, you got a bit lucky:

As of Qt 4.8, it's possible to draw into a QGLFramebufferObject using a QPainter in a separate thread. Note that OpenGL 2.0 or OpenGL ES 2.0 is required for this to work. Also, under X11, it's necessary to set the Qt::AA_X11InitThreads application attribute.

Here is what you have to do:

  • When operating under X11, use Qt::AA_X11InitThreads application attribute
  • Use a QGLWidget, QGLPixelbuffer or QGLContext in GUI thread to create a context and a QGLFramebufferObject that you want to draw into
  • Release the context in GUI thread via doneCurrent()
  • In the drawing thread, call makeCurrent() on the context, then use QPainter to do the drawing on the QGLFramebufferObject. You can use beginNativePainting()/endNativePainting() for raw OpenGL commands.
  • In the GUI thread, call toImage() on the framebuffer object to obtain a QImage or use drawTexture() on the QGLWidget.

Important: QGLContext is not thread-safe, so you might need to make sure you don't use the context in several threads at a time.

ypnos
  • 50,202
  • 14
  • 95
  • 141