如何从QGraphicsScene/QGraphicsView创建图像文件?

29

在给定一个 QGraphicsSceneQGraphicsView 的情况下,是否可以创建一个图片文件(最好是PNG或JPG格式)?如果可以,应该如何实现?

3个回答

35

我刚刚解决了这个问题,这里有足够的改进之处值得一个新答案:

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

31

我没有尝试过这个,但是这是实现它的思路。

你可以用几种方式来做到这一点。其中一个形式如下:

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. 
另一种方法是使用QGraphicsScene::render()函数进行渲染:

另一种方法是使用QGraphicsScene::render()函数进行渲染:

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

2
太棒了!谢谢。我尝试了第二种方法。唯一需要的是初始化QImage - Donotalo

9

grabWidget 已过时,请使用 grab。您可以使用 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
我测试了你的解决方案和Petrucio的解决方案。两个都可以,非常感谢。我更喜欢你的解决方案 :) ,因为它更短。 - Angie Quijano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接