[Qt-interest] MainWindow::paintEvent() constantly called

Alexandre Courbot gnurou at gmail.com
Fri Jun 19 06:32:12 CEST 2009


> The painEvent() is called constantly, if I don't prevent it.
> The side effects are that the image on screen is constantly updated and the
> CPU is overworked. This is not what I want.
> I want an image update every 1 or two seconds.
>
> void MainWindow::Setup()
> {
>   pView = ui->ViewLable;
>   pCamera = new CCamera(CSize(CameraImageWidth, CameraImageHeight));
>   pQImage = NULL;
>   GrabTimer = new QTimer(this);
>   connect(GrabTimer, SIGNAL(timeout()), this, SLOT(update()));
>   GrabTimer->start(2000);
> }
>
> // If I don't do the "Doneit" nonsense, this function will be called
> repeatedly, immediately after it exits.
> //
> // If I disable the timer and remove the "Doneit" code
> // the ViewLable ('pView' as it's called here) is constantly updated with
> camera output
> // i.e. there is a constant flow of live frames to the ViewLable
>
> void MainWindow::paintEvent(QPaintEvent *)    // how do I use QPaintEvent?
> {
>   static bool Doneit = false;
>
>   if(!Doneit)
>   {
>       if(pCamera->IsValid())
>       {
>           MyImage *p = pCamera->GetImage();
>           delete pQImage;
>           pQImage = new QImage(p->GetPixelAddress(0, 0), p->GetWidth(),
> p->GetHeight(), QImage::Format_RGB888);
>           QPixmap newPixMap = QPixmap::fromImage(*pQImage);
>           pView->setScaledContents(true);
>           pView->setPixmap(newPixMap);
>           Doneit = true;
>       }
>   }
>   else
>       Doneit = false;
> }

I guess your problem is that you trigger a paint event by yourself
within the paintEvent method. I'm not exactly sure what's wrong
though. What happens if you comment the setPixmap call out in
paintEvent? (not sure about it, but maybe that method calls update()
on its parent to schedule another paint event?)

Maybe a cleaner way to do that would be to have a custom slot called
by the timer (instead of update()) and to do everything in that slot.
You GUI will then be updated appropriately. In any case, you should
try to avoid overloading paintEvent as much as possible since it's the
best way to have this kind of problems.

> I just realized that I hit reply to your email and sent it to your gmail. Should
> I have sent it to qt-interest at trolltech.com?

Actually, yes. Please use "reply to all" for mailing-list messages.

> Sorry, first time user.

No problem, you're welcome.

Alex.




More information about the Qt-interest-old mailing list