OpenGL in a different thread in Qt5
-
I am trying to migrate my correctly working software from Qt4.8 to Qt5.4, but am facing segmentation faults. I have found other people with same kinds of problems, but nobody seems to have a solution.
I have a GLVideoWidget class that inherits QGLWidget. I need to use a swapInterval of 1 in my QGLFormat and draw 60 frames per second and thus need to do the drawing and buffer swapping in a different thread to avoid the GUI thread from stalling. I accomplished this in Qt4.8 by basically doing the following in my GLThread class:
while(!shouldStop) { if(shouldSwap_) { glw_->makeCurrent(); shaderProgram_.bind(); shaderProgram_.setUniformValue("texture", 0); shaderProgram_.setAttributeArray("vertex", vertices_.constData()); shaderProgram_.enableAttributeArray("vertex"); shaderProgram_.setAttributeArray("textureCoordinate", textureCoordinates_.constData()); shaderProgram_.enableAttributeArray("textureCoordinate"); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, VIDEO_WIDTH, VIDEO_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, (GLubyte*)imBuf_); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 6); glw_->swapBuffers(); shaderProgram_.disableAttributeArray("vertex"); shaderProgram_.disableAttributeArray("textureCoordinate"); shaderProgram_.release(); glw_->doneCurrent(); } }
Here glw_ is my GLVideoWidget. I have set autoBufferSwap to false so I call swapBuffers explicitely. All this worked fine before in Qt4.8, but now I get "Cannot make QOpenGLContext current in a different thread" and a segfault. Why? If I try to add context()->moveToThread(glt_); to my GLVideoWidget I get a segfault immediately. How should this be accomplished in Qt5?
-
I'm not that familiar yet with Qt5. But some tutorials encourage to use QOpenGLWidget instead of QGLWidget as base class now. It seems to implement a different buffer handling, as the autoBufferSwap attribute does not exist anymore. This might solve your threading issues.