开发者

Capture Qt widget as an image file

开发者 https://www.devze.com 2022-12-08 19:07 出处:网络
I\'m working with QGLWidget (Qt widget for OpenGL) and want to be able to capture the screen 开发者_如何学Pythondisplayed by the widget as JPEG files. How can I achieve this? Is there a function that

I'm working with QGLWidget (Qt widget for OpenGL) and want to be able to capture the screen 开发者_如何学Pythondisplayed 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.


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


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);


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


QPixmap pixmap = QPixmap::grabWidget( &widget );
pixmap.save("widget.png");


Improved version of @roop's answer.

QPixmap pixmap(mywidget.sizeHint());
QPainter painter(&pixmap);
mywidget.render(&painter);
pixmap.save("/some/file.png");

Changes:

  • using pixmap instead of image
  • using size hint instead of size
  • saving to lossless PNG instead of JPEG

Note that for this to work, the widget does NOT need to be displayed on screen.

0

精彩评论

暂无评论...
验证码 换一张
取 消