Search code examples
qtopengljpeg

Capture Qt widget as an image file


I'm working with QGLWidget (Qt widget for OpenGL) and want to be able to capture the screen displayed by the widget as JPEG files. How can I achieve this? Is there a function that return what is currently displayed on the widget as an image?


Solution

  • Normally with OpenGL, you would read from the framebuffer using the glReadPixels() function. This will put the framebuffer contents into a buffer that you have allocated. You then need a function that will convert this to JPEG.

    However, as you are using QGLWidget, you can use its grabFrameBuffer() method to obtain the frame buffer contents as a QImage object. This is probably the better way to go. You can grab the framebuffer contents, then use QImage::save() to save to a file.

    If you move to Qt 5's QOpenGLWidget, you'll find it has a similar grabFrameBuffer() method.