Save QWidget as image

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

Developers working with Qt can easily save the visual content of a QWidget as an image for later reference. This process involves instantiating a QPixmap object, sized to match the target QWidget using its size() method. The widget's current rendering is then captured onto this QPixmap using its render() method. Finally, the populated QPixmap can be saved to a file in various supported formats like PNG or JPEG, providing a straightforward way to persist widget visuals.

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

  COMMENT

1
Anonymous
Sep 22, 2018 at 6:48 pm

Great stuff!