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

How to create image file from QGraphicsScene/QGraphicsView?

本文关键字:创建 图像 文件 QGraphicsView QGraphicsScene      更新时间:2023-10-16

给定QGraphicsSceneQGraphicsView,是否可以创建图像文件(最好是PNG或JPG)?如果是,怎么做?

在处理了这个问题之后,这里有足够的改进来保证新的答案:

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

我没有尝试过,但这是如何做到这一点的想法。

您可以通过几种方式完成此操作一种形式如下:

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():
QImage image(fn);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
scene.render(&painter);
image.save("file_name.png")

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