How to create image file from QGraphicsScene/QGraphicsView ?
How to create image file from QGraphicsScene/QGraphicsView ?
Image file from QGraphicsScene/QGraphicsView:
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.
Give the function QGraphicsScene::render():
QImage image(fn); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); scene.render(&painter); image.save("file_name.png")
The following alternative code is :
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");
The grabWidget is derogat and to 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); }