Alex Rivera | Logout

How to create image file from QGraphicsScene/QGraphicsView?

Asked 2011-09-16T22:59:08.980
31

Given a QGraphicsScene, or QGraphicsView, is it possible to create an image file (preferably PNG or JPG)? If yes, how?

Edit
Report

1 Answer

37

After just dealing with this problem, there's enough improvement here to warrant a new answer:

scene->clearSelection();                                                  // Selections would also render to the file
scene->setSceneRect(scene->itemsBoundingRect());                          // Re-shrink the scene to it's bounding contents
QImage image(scene->sceneRect().size().toSize(), QImage::Format_ARGB32);  // Create the image with the exact size of the shrunk scene
image.fill(Qt::transparent);                                              // Start all pixels transparent

QPainter painter(&image);
scene->render(&painter);
image.save("file_name.png");
answered 2012-07-25T04:01:35.587

Your Answer