Save QWidget as image

  Peter        2012-08-19 12:01:18       27,530        1    

Qt library is an excellent GUI library for C++ programmers developed by Nokia and now is an open source project. Often, we may use QPainter to draw strings, lines or images on a QWidget. We can override the QWidget's paintEvent() method when we want to use QPianter object to draw something on a QWidget.

If we want to save the items drawn on QWidget as image for later reference, what can we do? We can save a QWidget as an image. Here is the code for achieving this:

QPixmap pixmap(this->size());

this->render(&pixmap);

pixmap.save("test.png");

Quite simple, right? Yes, these are all the codes you need. Here this refers to any QWidget pointer, it has a size() method which returns the size of the QWidget, the pixmap will use this value to create the image with the same size. Later, we need to use the render() method to render the contents of widget to the QPixmap object. Finally, we need to save the rendered contents to an image.

The following table shows the image file format supported by QPixmap.

FormatDescriptionQt's support
BMP Windows Bitmap Read/write
GIF Graphic Interchange Format (optional) Read
JPG Joint Photographic Experts Group Read/write
JPEG Joint Photographic Experts Group Read/write
PNG Portable Network Graphics Read/write
PBM Portable Bitmap Read
PGM Portable Graymap Read
PPM Portable Pixmap Read/write
XBM X11 Bitmap Read/write
XPM X11 Pixmap Read/write

C++  IMAGE  QT  QWIDGET 

       

  RELATED


  1 COMMENT


Anonymous [Reply]@ 2018-09-22 18:48:07

Great stuff!



  RANDOM FUN

This is really spicy I believe