Section 14.6 (Simple animation) in Stroustrup’s “Programming Principles and Practice using C++” third edition uses his PPP graphics library, which in turn makes use of QT. I am trying to understand what is involved.
The following program works as intended: initially it displays two black circles. After 2 seconds the first circle changes color to red. After four more seconds the second circle changes color to blue.
Stroustrup writes: “You can also add an action (“callback”) as an argument. That action is invoked after the delay”. So I experimented by replacing the indicated lines of code with code that does this. I expected the output to be exactly the same, but it is not. At two seconds nothing happens, but at four seconds both circles change color at the same time.
#include "PPP/Simple_window.h"
#include "PPP/Graph.h"
int main(int /*argc*/, char * /*argv*/[])
{
using namespace Graph_lib;
Application app;
// Window initially displays 2 black circles
Simple_window w {Point{0,0}, 600, 400, "Callback problem"};
Circle c1{{175, 200}, 100};
Circle c2{{425, 200}, 100};
c1.set_fill_color(Color::black);
c2.set_fill_color(Color::black);
w.attach(c1);
w.attach(c2);
// Code to be replaced:
w.timer_wait(2000); //2000 milliseconds
c1.set_fill_color(Color::red);
w.timer_wait(4000);
c2.set_fill_color(Color::blue);
//////////////////////////////
// // I expected this code to have the same result:
// w.timer_wait(2000, [&]{c1.set_fill_color(Color::red);});
// w.timer_wait(4000, [&]{c2.set_fill_color(Color::blue);});
// //////////////////////////////////////////////
w.wait_for_button();
}
Why is the output not the same? Is there something I can do to use the callback method successfully?