Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does QPainter::save () and QPainter::restore () do?

Tags:

qt

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?

like image 496
yan bellavance Avatar asked Jun 10 '10 17:06

yan bellavance


3 Answers

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.

like image 71
Frank Osterfeld Avatar answered Nov 06 '22 18:11

Frank Osterfeld


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.

like image 40
mtvec Avatar answered Nov 06 '22 20:11

mtvec


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.

like image 10
Harald Scheirich Avatar answered Nov 06 '22 19:11

Harald Scheirich