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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7451183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:57:31  来源:igfitidea点击:

How to create image file from QGraphicsScene/QGraphicsView?

c++imageqtgraphics

提问by Donotalo

Given a QGraphicsScene, or QGraphicsView, is it possible to create an image file (preferably PNG or JPG)? If yes, how?

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

回答by Petrucio

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

回答by jordenysp

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():

另一种是使用渲染函数QGraphicsScene::render():

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

回答by amdev

grabWidget is deprecated, use grab. And you can use a QFileDialog

不推荐使用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);
    }