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 库是诺基亚开发的,现在是一个开源项目,是 C++ 程序员的优秀 GUI 库。通常,我们可能会使用 QPainter 在 QWidget 上绘制字符串、线条或图像。当我们想使用 QPianter 对象在 QWidget 上绘制内容时,可以重写 QWidget 的 paintEvent() 方法。

如果我们想将 QWidget 上绘制的项目保存为图像以供日后参考,我们该怎么做?我们可以将 QWidget 保存为图像。以下是实现此目的的代码:

QPixmap pixmap(this->size());

this->render(&pixmap);

pixmap.save("test.png");

很简单,对吧?是的,这些就是您需要的所有代码。这里的 this 指的是任何 QWidget 指针,它有一个 size() 方法,该方法返回 QWidget 的大小,pixmap 将使用此值创建大小相同的图像。稍后,我们需要使用 render() 方法将 widget 的内容渲染到 QPixmap 对象。最后,我们需要将渲染的内容保存到图像。

下表显示了 QPixmap 支持的图像文件格式。

格式描述Qt 的支持
BMP Windows 位图 读/写
GIF 图形交换格式(可选) 读取
JPG 联合图像专家组 读/写
JPEG 联合图像专家组 读/写
PNG 便携式网络图形 读/写
PBM 便携式位图 读取
PGM 便携式灰度图 读取
PPM 便携式像素图 读/写
XBM X11 位图 读/写
XPM X11 像素图 读/写
C++ IMAGE QT QWIDGET

  RELATED

  COMMENT

1
Anonymous
Sep 22, 2018 at 6:48 pm

Great stuff!