tags:

views:

96

answers:

3

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?

+5  A: 

From http://doc.qt.nokia.com/4.6/qpainter.html#settings:

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.

Job
To elaborate, this lets you do things like, for example: you set up a pen, do some drawing, save, change the pen, do some drawing, restore, do some more drawing with the original pen.
Dan
+1  A: 

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.

Frank
(see QMutexLocker for the same concept)
Frank
Does not really answer the question but good idea
Harald Scheirich
+1  A: 

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

Harald Scheirich