PDA

View Full Version : Help:Export QGraphicsView to Image File



cometyang
26th December 2007, 23:17
Hi, All.

I'm trying to export the GraphicsScene's content to Image File.
And I use the code example from the documentation.


QGraphicsScene scene;
scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green));

QPixmap pixmap;
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
scene.render(&painter);
painter.end();

pixmap.save("scene.png");


However, it failed.

The error message show that:
QPainter::begin:Cannot paint on a null pixmap
QPainter::setRenderHint: Painter must be active to set rendering hints
....

Anyone know what's wrong with the example code(I already correct some error in the given documentation)

I use Qt 4.3.2 on Linux platform

marcel
26th December 2007, 23:25
That's because, as the warning says, you're painting on a null pixmap. You first need to initialize the pixmap to the scene's size.
See QGraphicsScene::sceneRect()

wysota
26th December 2007, 23:43
The size doesn't have to be the size of the scene. This is perfectly correct:

QGraphicsScene scene;
//...
QImage img(1024,768,QImage::Format_ARGB32_Premultiplied);
QPainter p(&img);
scene.render(&p);
p.end();
img.save("XXX.png");

marcel
26th December 2007, 23:45
The size doesn't have to be the size of the scene. This is perfectly correct:

QGraphicsScene scene;
//...
QImage img(1024,768,QImage::Format_ARGB32_Premultiplied);
QPainter p(&img);
scene.render(&p);
p.end();
img.save("XXX.png");
I assumed he wanted to export the entire scene. Of course, the output image can be initialized to any size, as long as it is not (0,0).

cometyang
27th December 2007, 00:13
Thanks for your help.

The problem solved:D!

wysota
27th December 2007, 00:39
I assumed he wanted to export the entire scene.

If you don't pass the size to QGraphicsScene::render(), it will always draw the entire scene. The painter (image) size is only to determine the scale which is to be used to draw the scene.