Search code examples
qtqpainter

Using QPainter with QPaintDevice multiple times


we all know this Warning from

bool QPainter::​begin(QPaintDevice * device)   

Warning: A paint device can only be painted by one painter at a time.

http://doc.qt.io/qt-5/qpainter.html#begin

But what if I have two object sharing one pixmap, and one object Bar contains other object Foo.

class Foo
{
public:
    QPixmap* barPixmap;
    void draw()
    {
         QPainter painter(barPixmap);
         painter.drawText(0,0,"FooText");
    }

}

class Bar
{
public:
    QPixmap* barPixmap;
    Foo*     fooObject;
}

and I got something like this

Bar::paintEvent(QPaintEvent* )
{
    QPainter painter(barPixmap);
    painter.drawText(50,50,"BarText");
    fooObject->draw();

}

Is it multiple drawing? Compiler throws nothing and code seems working.


Solution

  • The warning tells you about creating multiple QPainters at one time. Since all paint events are processed in the main thread, they are processed consequently. As long as QPainter object is destroyed at the end of your event handler, the warning will not appear. Multiple consequent paintings on one device is fine.

    However the architecture is questionable. For instance, if multiple widgets are painted this way, one of widgets will display old version of pixmap while second widget will display updated version. This inconsistency can be a problem. Putting any logic in paint event handlers is generaly pointless (and sometimes harmful). You should change pixmap when available data changes and just paint it in the paint event.