[Qt-interest] Optimizing QPaintEvent and clipping

Josh jnfo-c at grauman.com
Mon Feb 9 04:17:25 CET 2009


Hello,

I'm trying to reimplement QPaintEvent for a class subclassed from QWidget. 
I'm using a QPainter to paint a number of shapes (QRects in my example, ie 
QList<QRect> rects) onto the QWidget. Having gotten that to work, I'm 
trying to improve speed by only redrawing the parts of the widget that 
need repainting. I can see that QPaintEvent gives a QRect of the part of 
the widget that needs repainting. I thought the following would work:

1) Set the painter clip rectangle to be only the part that needs updating.
    The docs seemed to indicated that QPainter did this automatically
    anyway, but I wasn't sure. ?? Anyone know ??
2) Clear the rectangle that needs updating.
3) (Re)draw any rectangles that intersect with the rectangle that needs
    updating.

I tried the following code to implement that, but it doesn't work. In 
particular, when the rects get covered and then uncovered, they aren't 
fully redrawn. Are there any simple examples that do this? Any pointers on 
what I'm doing wrong? Thanks so much.

Josh

void Widget::paintEvent(QPaintEvent *e)
{
   QPainter painter(this);
   {
     painter.setRenderHint(QPainter::Antialiasing, true);
     painter.setClipRect(e->rect());
     painter.fillRect(e->rect(),QColor(0,0,0,0));
     int i;
     for(i=0;i<rects.size();i++)
     {
       if(e->rect().intersects(rects[i]))
       {
         QPen pen;
         pen.setColor(QColor(100,0,100));
         pen.setWidth(2);
         painter.setPen(pen);
         painter.drawRect(rects[i]);
       }
     }
   }
}



More information about the Qt-interest-old mailing list