2011-09-16 10 views

Respuesta

20

No he probado esto, pero esta es la idea de cómo hacerlo.

Puede hacerlo de varias maneras Una forma es como sigue:

QGraphicsView* view = new QGraphicsView(scene,this); 
QString fileName = "file_name.png"; 
QPixmap pixMap = QPixmap::grabWidget(view); 
pixMap.save(fileName); 
//Uses Qpixmap::grabWidget function to create a pixmap and paints the QGraphicsView inside it. 

La otra es utilizar la función de hacer que QGraphicsScene :: render():

QImage image(fn); 
QPainter painter(&image); 
painter.setRenderHint(QPainter::Antialiasing); 
scene.render(&painter); 
image.save("file_name.png") 
+1

¡increíble! Gracias. intenté el segundo enfoque. lo único que se requiere es que 'QImage' necesite ser inicializado. – Donotalo

25

Después sólo se ocupan con este problema, hay suficiente mejora aquí para justificar una nueva respuesta:

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"); 
6

grabWidget está en desuso, use agarrar. Y puede usar un 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); 
    } 
+1

He probado su solución y la solución * Petrucio *. Ambos funcionan, muchas gracias. Me gusta más tu solución :), es más corta. –

Cuestiones relacionadas