简体   繁体   中英

Use one QPainter to paint multiple outputs at once: SVG and QImage

My Qt application uses a QPainter to draw a vector graphic. I need this graphic output twice, once as a vector output in SVG format, where I'm using QSvgGenerator, and once as a pixel format, where I'm using QImage. According to what I've found in the documentation I can either first paint to SVG and then convert the SVG output to a Qimage:

QPainter painter;
QSvgGenerator generator;
generator.setSize(QSize(width_, height_));
// more initializations here
painter.begin(&generator);
doPaintMyStuff(&painter);
painter.end();
generator.setOutputDevice(...)   // pipe the SVG output to the server
QImage image(width_, height_, QImage::Format_ARGB32_Premultiplied);
QSvgRenderer renderer;
renderer.load(...)                // get the svg output we just generated
painter.begin(&image);
renderer.render(&painter);       // render the vector graphic to pixel
painter.end();
usePixelData(image.constBits()); // pipe the pixel output to the server

or draw twice using two different backends:

QPainter painter;
QSvgGenerator generator;
generator.setSize(QSize(width_, height_));
// more initializations here
QImage image(width_, height_, QImage::Format_ARGB32_Premultiplied);
painter.begin(&generator);
doPaintMyStuff(&painter);
painter.end();
painter.begin(&image);
doPaintMyStuff(&painter);
painter.end();
generator.setOutputDevice(...)   // pipe the SVG output to the server
usePixelData(image.constBits()); // pipe the pixel output to the server

Both solutions work, but both seem terribly inefficient to me, since I'm always drawing the same scene twice. The latter calls all functions on QPainter twice, the former draws all operations again by re-tracing the SVG ouput I just generated.

Is there a way to attach multiple backends to one QPainter to paint the whole scene only once?

I don't think you can get what you want out of the box. You could dig into the private implementation of the painter and come up with a way to do everything just once - generate each vector painter component and rasterize it to another paint device and move onto the next, but it will probably not be simple and hardly be worth it.

Just profile the two solutions you have so far and stick to the faster one, looks like the first one might be a tad more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM