I am not certain what it is that QPainter
does when I invoke save()
and restore()
.
Is it saving the image it is drawing or is it just saving information like penWidth
and color
etc.?
Could I use it to restore the image of a previous paint event?
If one uses save/restore a lot, it's nice to have a little RAII class ("PainterSaver") to make sure each save() (done in the ctor) has a corresponding restore() call (done in the dtor), otherwise one can run into nasty "unbalanced save/restore" errors.
From the documentation:
You can at any time save the QPainter's state by calling the save() function which saves all the available settings on an internal stack. The restore() function pops them back.
All those settings are listed at the given link. So it is just saving the paint settings and nothing that's actually painted.
As you are probably changing the color and style or any other settings of the paint you usually want to exit your paint function with the same settings that it had when coming in. Therefore you use QPainter::save()
before a change in painter settings and QPainter::restore()
after you are done drawing with your changed settings e.g.
void paint( QPainter* painter,
const QStyleOptionGraphicsItem* option,
QWidget* widget = 0 )
{
// Painter has certain settings
painter->save();
QPen pen = painter->pen();
pen.setColor(QColor(200,20,20);
// Changing settings of painter
painter->setPen(pen);
// ... Draw
painter->restore();
// Painter has same settings as on entry into this function
}
painter->save()
puts the state of the painter on a stack, painter->restore()
pulls the state from the stack and changes the settings to match that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With