Capturing a Qt widget as an image file

I work with QGLWidget (Qt widget for OpenGL) and want to be able to display the screen displayed by widgets as JPEG files. How can i achieve this? Is there a function that returns what is currently displayed in widgets as an image?

+4
source share
5 answers

Usually with OpenGL you read from the framebuffer using the glReadPixels() function. This will place the contents of the framebuffer in the buffer you select. Then you need a function that converts it to JPEG.

However, since you are using QGLWidget , you can use the grabFrameBuffer() method to get the contents of the frame buffer as a QImage object. This is probably the best way. You can capture the contents of the framebuffer and then QImage::save() to a file.

If you go to Qt 5 QOpenGLWidget , you will see that it has similar grabFrameBuffer() .

+12
source
 QImage img(mywidget.size()); QPainter painter(&img); mywidget.render(&painter); img.save("/some/file.jpg"); 
+9
source

Why not use the very simple QPixmap::grabWindow( m_widget->winId() ).save( "/some/file.jpg" )

+1
source

Here is the easiest way to save the widget as an image while 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); 
+1
source
 QPixmap pixmap = QPixmap::grabWidget( &widget ); pixmap.save("widget.png"); 
-3
source

All Articles