Answer the question
In order to leave comments, you need to log in
How to make a delay in a Qt loop so that the UI thread does not stop?
I need to make a delay in the code during the for loop, but so that the Ui thread does not stop (the sleep function will not help). A mockup of what it should look like: below .
void View::viruspodMoving(QGraphicsItem *virus) { // функция, не слот
for(int y = vir.y; y < 501;){
delay() // реализованная задержка
y = y + 4;
vir.y = vir.y + 4;
virus->setPos(vir.x, y);
}
if(vir.y >= 500){
deleteVirus(virus);
}
}
Answer the question
In order to leave comments, you need to log in
You need to separate this by thread. Data separately, yuai separately.
Although apparently in Qt you are trying to make a game, this is done if something is completely wrong:
- implement a certain function, let's call it Update, and make it so that it is called 60 times per second (approximately)
- it is in this function that you output graphics
- it is in this function that you make the movement, but without delays, and with reference to the frequency of the function call (more precisely, to the time since the previous call)
- but with the input it is more interesting - it must be processed separately and cumulatively
You were answered correctly above, it is necessary to separate into different streams. But if, nevertheless, you want to write a delay in the UI thread, then here
void delay(int ms)
{
QElapsedTimer et;
et.start();
while(true)
{
qApp->processEvents();
if(et.elapsed() > ms) break;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question