PDA

View Full Version : QPainter::save and QPAinter::restore()



quickNitin
16th June 2006, 11:26
In doc it says QPainter::save() saver the curent state of painter and restore do restore(). I couldn't find out what it mean state of QPainter. I tried without them also i got output.

What is the significance of these 2 function and state of a painter.

wysota
16th June 2006, 12:01
It's really usefull if you want to modify some of QPainter's attributes for a short while and then set it back. For example imagine that you want to draw a part of the "image" rotated, with a different font and colour. Without QPainter::save/restore you'd need to do:


painter->rotate(90);
QFont oldfont = painter->font();
QPen oldpen = painter->pen();
painter->setFont(QFont(...));
painter->setPen(QPen(...));
painter->drawText(...);
painter->setFont(oldfont);
painter->setPen(oldpen);
painter->rotate(-90);

The same thing with save and restore:

painter->save();
painter->rotate(90);
painter->setFont(QFont(...));
painter->setPen(QPen(...));
painter->drawText(...);
painter->restore();

This example is simple but imagine you have to do more transformations and them restore the state of the painter before the operation, because something else will want to paint on it too and expects some "default" settings. Save/restore pair is very handy here. I think it came from OpenGL world where you can save/restore the state of matrices.

bits
17th June 2006, 22:11
save() and restore() are particularly useful for building hierarichal models.

For example a robot:

painter->save();

translate, scale, or rotate the torso;
draw the torso;

painter->save();
translate, scale, or rotate the left hand;
draw the left hand;
painter->restore();

painter->save();
translate, scale, or rotate the right hand;
draw the right hand;
painter->restore();

painter->restore();

The right hand has nothing to do with the left hand's transformations. If either hands move, nothing else changes; However if the torso moves, both the hands move as well.


I think it came from OpenGL world where you can save/restore the state of matrices.
As Wysota said, we use such a concept widely in OpenGL programming.
*OpenGL's equivalent is glPushMatrix() and glPopMatrix()