Repaint screen every little time without crashing - C++

Asked

Viewed 213 times

4

I have the following situation:

I have to repaint the screen every little while so that objects on the screen move on their own, but this has to occur so that the program does not lock.

I tried to make a Thread and call the update method but the screen is white, all locked.

Basically, I need this to occur at each specific time, but that does not influence the after processes of the program (such as keyboard and mouse events).

void atualizar(){
   X = X - 20;
   repaint();
}

I believe that the best is with Thread, but I could not implement in the right way, even following the official QT documentation.

Another point, when trying to do with Thread the painting event ends up being called twice, occurring in crash in the program.

1 answer

4


One solution would be to use a Qtimer:

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(repaint()));
timer->setInterval(200); // 200 milissegundos
timer->start(); // Se preferir, pode usar start(200) e remover a linha do setInterval

Remember that all GUI operations should be done on the main thread, and when you need to use other threads, communication should be done by SIGNALS and SLOTS, never calling methods directly between threads.

When you need to turn off the timer, just call timer->stop(); and to reactivate, just new call to timer->start();

See more details on manual qt.

  • Very good your answer. I am very grateful to have solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.