Aria
Aria

Reputation: 97

C++ Sleep function doesn't work as is expected

I'm going to first draw a polygon on the window and after one second remove that polygon and draw a circle instead. I wrote this code for it:

#include <Simple_window.h>
#include <Graph.h>

using namespace Graph_lib;

//------------------------------------------------------------------------------
int main() {
    Simple_window win(Point(100,100),600,400,"lines");

    Graph_lib::Polygon poly;
    Circle c(Point(100,150), 50);

    poly.add(Point(100,100));
    poly.add(Point(150,150));
    poly.add(Point(50,100));
    win.attach(poly);
    Sleep(1000);
    win.detach(poly);
    win.attach(c);
    win.wait_for_button();
    return 0;
}

But it doesn't occur this way in practice. In fact the system just waits one second and shows the circle (c) only and the polygon (poly) will not be shown!

How to solve the problem please?

Upvotes: 0

Views: 1220

Answers (1)

LPs
LPs

Reputation: 16243

Call Sleep function inside your main will freeze the application, and repaint/refresh at all.

To do what yiu need you have to use a timer or a thread used as timer where to put your code and manage delays.

Code inside your timer event could be like this

Call Sleep function inside your main will freeze the application, and repaint/refresh at all.

To do what yiu need you have to use a timer or a thread used as timer where to put your code and manage delays.

Code inside your timer event could be like this, I know the code is not correct at all, it is a trace.

Graph_lib::Polygon poly;
Circle c;

void OnTimerEvent()
{
      win.detach(poly);
      win.attach(c);
}

int main()
{
    c(Point(100,150), 50);
    poly.add(Point(100,100));
    poly.add(Point(150,150));
    poly.add(Point(50,100));
    win.attach(poly);

    timer.interval = 1000;
    timer.enabled = true;

    win.wait_for_button();
}

What I mean is that you have to launch a timer which event will be called after 1 second and can do your stuff.

Upvotes: 2

Related Questions