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 函式庫是個由 Nokia 開發,現在是開放原始碼專案的 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!