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?
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.
Here is the simplest way to save widget as an image, working on Qt 5:
QString file = QFileDialog::getSaveFileName(this, "Save as...", "name", "PNG (*.png);; BMP (*.bmp);;TIFF (*.tiff *.tif);; JPEG (*.jpg *.jpeg)");
ui->myWidget->grab().save(file);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With