Qt Snippet: " Painter not active " error

If you subclass a widget control and try to repaint the content by overriding the paintEvent() method you could experiment, for some specific type of Qt widgets, the error "Painter not active". This error come up during program execution when try to create the QPainter object for draw the widget content.


The problem usually came from the use of the wrong QPaintDevice pointer. Some Qt widgets, like for example QGraphicsView, have an additional "internal" paint area usually called viewport that need to be used for paint instead of the main object. Translating this explanation into code we can use as example the subclass of the QGraphicsView as follow:

void MyGraphicsView::paintEvent(QPaintEvent * event)
{
    QPainter painter(this);

    // Here draw the content
}

This code will show up the "Painter not active" error because for this specific widget the internal viewport have to be used. The correct code will be the following:

void MyGraphicsView::paintEvent(QPaintEvent * event)
{
    QPainter painter(viewport());

    // Here draw the content
}

Through the call viewport() we get the working QPaintDevice pointer to use for paint widget area.

Comments

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model