Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture Qt widget as an image file

Tags:

jpeg

qt

opengl

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?

like image 491
ejel Avatar asked Oct 15 '09 04:10

ejel


2 Answers

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.

like image 162
MichaelM Avatar answered Oct 12 '22 21:10

MichaelM


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);
like image 23
Danio Avatar answered Oct 12 '22 20:10

Danio