Question

I'm trying to use QPainter to draw items onto a QImage , but since I can't predict the exact size of this QImage , I can't use QImage::save() , it always tell me:

QPainter::begin: Paint device returned engine == 0, type: 3

But if I specify the image height and width when declaring this QImage , it works smoothly:

QImage output = QImage (500 , 500 , QImage::Format_ARGB32);

Was it helpful?

Solution

QImage, QPixmap, etc. require data to be allocated before drawing can begin. Using the default constructor of QImage does not allocate any memory, so image.isNull() == true. So when you call QPainter::begin() (probably indirectly by creating one with the QImage as the paint device) it can't draw into any memory because it isn't there.

From the QPainter::begin() docs:

QPixmap image(0, 0);
painter->begin(&image); // impossible - image.isNull() == true;

So you have to come up with a size before drawing. In your situation, the best thing to do would be to decide on a maximum size (or calculate one if feasible), and then once you do know the exact size - crop the image.

OTHER TIPS

Alternatively, you can draw on a QGraphicsScene which will expand automatically as you add items on it, then save only the painted area given by QGraphicsScene::itemsBoundingRect():

QGraphicsScene scene;
scene.addItem(...);

QImage image(scene.itemsBoundingRect().size(), QImage::Format_ARGB32);

QPainter painter(&image);
scene.render(&painter, image.rect(), scene.itemsBoundingRect());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top