How to create image file from QGraphicsScene/QGraphicsView?
Given a QGraphicsScene, or QGraphicsView, is it possible to create an image file (preferably PNG or JPG)? If yes, how?
Answers
I have not tried this, but this is the idea of how to do it.
You can do this in several ways One form is as follows:
QGraphicsView* view = new QGraphicsView(scene,this); QString fileName = "file_name.png"; QPixmap pixMap = view->grab(view->sceneRect().toRect()); pixMap.save(fileName); //Uses QWidget::grab function to create a pixmap and paints the QGraphicsView inside it.
The other is to use the render function QGraphicsScene::render():
QImage image(fn); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); scene.render(&painter); image.save("file_name.png")
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");
grabWidget is deprecated, use grab. And you can use a QFileDialog
QString fileName= QFileDialog::getSaveFileName(this, "Save image", QCoreApplication::applicationDirPath(), "BMP Files (*.bmp);;JPEG (*.JPEG);;PNG (*.png)" ); if (!fileName.isNull()) { QPixmap pixMap = this->ui->graphicsView->grab(); pixMap.save(fileName); }