Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QPainter - save and restore ?



  • Hi,

    I find this topic in stack "What does QPainter::save () and QPainter::restore () do?" . One user wrote:

    https://stackoverflow.com/questions/3016709/what-does-qpaintersave-and-qpainterrestore-do
    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.
    I check it:

    void MainWindow::paintEvent(QPaintEvent *event)
    {
    QPainter painter(this);
    static int i=0;
    if(i==0)
    {
    painter.setPen(Qt::red);
    }
    painter.drawEllipse(QPoint(100,100),10,10);
    i++;
    }
    And... when I go outside paintEvent function, the settings, which I changed, are reset to default ( I change pen to red, and when I go in paintEvent for the second time I still have default settings and draw with black color ). So why this user wrote that?

    I thought that restore and save funtions are only to help us in this situation:

    QPainter painter(this);
    painter.save();
    painter.setPen(Qt::red);
    ....  and many, many other change settings
    painter.restore();
    painter.drawEllipse(QPoint(100,100),10,10);    // <- here we have to draw this using default settings


  • @lich365net
    They are indeed to help the situation you show in your code. Changed setting do not persist once paintEvent() exits, there is nothing "permanent". I don't know what your question is other than that.


Log in to reply