Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
Donotalo Avatar asked Sep 16 '11 22:09

Donotalo


3 Answers

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");
like image 173
Petrucio Avatar answered Nov 05 '22 12:11

Petrucio


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")
like image 41
jordenysp Avatar answered Nov 05 '22 11:11

jordenysp


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);
    }
like image 9
amdev Avatar answered Nov 05 '22 12:11

amdev