How it works...

By default, QPainter will use the paint engine from its parent object to draw the graphics assigned to it. If you don't assign any parent to QPainter, you can manually assign a paint engine to it, which is what we have done in this example.

The reason why we placed the code into paintAll() is because we want to reuse the same code for two different purposes: for displaying the graphics on the window and exporting the graphics to an SVG file. Notice the default value of the generator variable in the paintAll() function is set to 0, which means no QSvgGenerator object is required to run the function unless specified. Later on, in the paintAll() function, we check whether the generator object exists. If it does exist, use it as the paint engine for the painter, as shown in the following code:

if (engine)
painter.begin(engine);
else
painter.begin(this);

Otherwise, pass the main window to the begin() function (since we're writing the code in mainwindow.cpp file, we can directly use this to refer to the main window's pointer) so that it will use the paint engine of the main window itself, which means the graphics will be drawn onto the surface of the main window. In this example, it's required to use a single QPainter object to save the graphics into the SVG file. If you use multiple QPainter objects, the resulting SVG file will contain multiple XML header definitions and thus the file will be deemed to be invalid by any graphics editor software out there.

QFileDialog::getSaveFileName() will open up the native save file dialog for the user to choose the save directory and set a desired filename. Once the user is done with that, the full path will be returned as a string and we will be able to pass that information to the QSvgGenerator object to export the graphics.

Notice that in the previous screenshot, the penguin in the SVG file has been cropped. This is because the canvas size of the SVG was set to follow the size of the main window. To help the poor penguin getting its body back, scale the window bigger before exporting the SVG file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset