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

Is it possible to redraw in paintEvent?



  • Hi,
    I have a widget ( inherits from QWidget ). I would like to draw a line on it, so I have method:

    void widget::paintEvent(QPaintEvent *event)
    {
         QPainter painter(this);
         if( drawLine == true )
         {
              painter.drawLine(0,0,100,100);
         }
    
         QWidget::paintEvent(event);
    }
    

    drawLine is bool variable, which I set in other method and after that I do repaint().

    Now I would like to change this method to:

    void widget::paintEvent(QPaintEvent *event)
    {
         QPainter painter(this);
         if( drawLine == true )
         {
              painter.drawLine(0,0,100,100);
         }
         if( drawOtherLine == true )
         {
              painter.drawLine(0,100,100,100);
         }
    
         QWidget::paintEvent(event);
    }
    

    I know that I first set drawLine variable ( and do repaint() ), and after that I set drawOtherLine variable ( and do repaint() ). When I do repaint() after set drawOtherLine I go to paintEvent and I have to draw 2 lines. And I would like to improve that. I would like to only draw the second line. Every time when I go to paintEvent I have to draw all over again. I would only like to draw this new Line and have 2 lines.

    Explain in the picture:

    Beza.png
    In paintEvent I draw only red lines. So after first repaint I would like to save image. I don't want redraw everything one more time. I only draw new things.



  • @TomNow99
    What you want to do runs counter to how QPainter is designed to work. There are ways to cache already painted stuff, but I would only start using that if I see a performance issue. And even if you use that -it will still paint everything - just faster.

    If it is all about lines and other simple shapes, you could create a QPainterPath with everything that needs to be drawn, and simply paint that.



  • Sounds like the Scribble Example.
    It draws the lines to a QImage and calls drawImage in the paintEvent.

    Otherwise AFAIK there's no something like "save image" in painting.
    You can call repaint with a QRect and then in paintEvent only draw within event->rect(), but that doesn't seem to be what you want.


Log in to reply