Chapter 7. Removing flicker using a timer

QTimer objects are used when you want to do something at a given time, or each x milliseconds. To do so, you can start a timer and it emits a signal in a given time. You then connect that signal to a slot that do some work and you're done.

First, we add a QTimer m_timer protected variable to CentralView (don't forget the corresponding #include <qtimer.h> include line). In the constructor of CentralView, we connect the signal timeout() that m_timer emits to the updatePixmap() slot that we created in s3. We use connect(&m_timer, SIGNAL(timeout()), this, SLOT(updatePixmap())); to do so.

Now, we change the three slots, setRed, setGreen and setBlue to start the timer instead of calling updatePixmap directly. m_timer.start(200,true); starts a singleshot timer (one that will emit only one signal and then stop) with a 200 ms. timeout. Each time we start a timer and another one is waiting to be timed out (we start the second timer before the 200 ms. have passed), the previous timer is stopped. That means that if the user moves the slider fast, instead of calling updatePixmap() many times, we're waiting for the user to stop moving the slider for 200 ms before making the actual call.

That makes s4. Now that we've fixed flicker (at least, it doesn't flicker much, as fixing it completely would be beyond the scope of this tutorial), we can go for more advanced experiences.