给定QGraphicsScene
或QGraphicsView
,是否可以创建图像文件(最好是PNG或JPG)?如果是,怎么样?
答案 0 :(得分: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");
答案 1 :(得分:28)
我没有尝试过,但这是如何做到这一点的想法。
您可以通过多种方式完成此操作 一种形式如下:
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")
答案 2 :(得分: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);
}