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

Don*_*alo 23 c++ graphics qt image

给定a QGraphicsScene,或者QGraphicsView,是否可以创建图像文件(最好是PNG或JPG)?如果有,怎么样?

Pet*_*cio 30

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

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");
Run Code Online (Sandbox Code Playgroud)


jor*_*ysp 29

我没试过这个,但这是怎么做的想法.

您可以通过多种方式执行此操作一种形式如下:

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. 
Run Code Online (Sandbox Code Playgroud)

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

QImage image(fn);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
scene.render(&painter);
image.save("file_name.png")
Run Code Online (Sandbox Code Playgroud)

  • 真棒!谢谢.我尝试了第二种方法.唯一需要的是`QImage`需要初始化. (2认同)

amd*_*dev 8

grabWidget已弃用,请使用抓取功能.你可以使用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);
    }
Run Code Online (Sandbox Code Playgroud)