How to create image file from QGraphicsScene/QGraphicsView ?

How to create image file from QGraphicsScene/QGraphicsView ?

Asked on January 8, 2019 in Qt.
Add Comment


  • 3 Answer(s)

    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")
    
    Answered on January 8, 2019.
    Add Comment

    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");
    
    Answered on January 8, 2019.
    Add Comment

    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);
       }
    
    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.