QtChart save to image file

The QtChart module was introduced in Qt 5.7. Using the QtChart module, you can easily draw various beautiful charts in the program. In addition to being displayed on the interface, these beautiful charts often need to be saved as pictures for subsequent use. This blog will talk about how to Chart is saved to the image.

In fact, this is a small problem, only two or three lines of code are needed. However, the QChartView class does not provide such a function. So to achieve such a small function, it is really necessary to test everyone's mastery of Qt.

The only way I use is to use QScreen:

QPixmap QScreen::grabWindow(WId window, int x = 0, int y = 0, int width = -1, int height = -1)

This method. With this method, as long as there is a WId, the image of any window can be obtained.
QChartView inherits from QWidget, and the WId can be obtained with the winId() function.

The following is the simplest code snippet describing how to save an image of a QChartView to a chart.png file:

    QScreen * screen = QGuiApplication::primaryScreen();
    QPixmap p = screen->grabWindow(view->winId());
    QImage image = p.toImage();
    image.save("chart.png");

The following is an image I obtained with this method. Before obtaining this image, I deliberately moved the chart view window out of the screen. After testing, this does not affect me getting the correct image.
write picture description here
According to my idea, as long as it is Windows inherited from QWidget can be saved as pictures.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325561399&siteId=291194637