Wait for the next action
-
Hi all!
Tell me, please, how can I make a delay before the next action. In this case, I still need to update the progress bar.
void ClassName::start() { action1(); /* Here I need to wait a while, update the progress bar, and go further */ action2(); emit finished(); }
I tried to do it this way, but it does not work.
void ClassName::start() { emit mainLabelEmit(QString("start")); QTimer *timer = new QTimer(this); timer->setSingleShot(true); timerCount = 10; //timer = new QTimer(); timer->start(timerCount * 1000); while (timer->remainingTime() >= 0) { QString smallLabel = QString("Left %1 sec").arg(timer->remainingTime() / 1000); //qDebug() << smallLabel; emit smallLabelEmit(smallLabel); if (timer->remainingTime() == 0) { timer->stop(); emit smallLabelEmit(QString("")); } else { emit progressBarEmit(100 - 100 * timer->remainingTime() / timerCount); } } for (int i = 0; i < 7; i++) { emit open(i); } for (int i = 0; i < 7; i++) { emit close(i); } emit finished(); }
Thanks!
-
Hi
Using a timer is a good idea but you should restructure the code so the timer slot can handle the the actions
Also do not use long for loop or while loop in Qt programs as it strangulate the event loop and make app not draw/seem to lag etc.Say u set the timer to 1 sec let it call timerslot (repetitive , not single slot)
and declare a long int as tick. ( as member in class)
tick=0;
timer->startvoid timerslot() {
if( tick ==0 )
Call action 1; // called at once
else if ( tick == 5 ) // 5 secs
Call Action 2// update bar if needed
...tick++; // progress "time"
}A better design would would involve action to signal its finished so then you run action 2
But for a fast fix, use the timer to count until next action should be performed.
Its not possible to wait in the main thread as you would then stop whole application from drawing.
So using timer, you are not blocking it and the wait its done by checking for time (ticks) and perform
action after X ticks. -
Hi,
What kind of action do you have in mind ? What's the workflow of your application ?
-
@SGaist said in Wait for the next action:
Hi,
What kind of action do you have in mind ? What's the workflow of your application ?
Hello,
I have an application for filling gas barrels. I open / close the valve, then I want to wait a few seconds to stabilize. After waiting, I open the drain valve. -
Then you should rather model that with a state machine. That would make more sense from a handling point of view.
-
@maratk1n Here the link to what @SGaist mentioned: http://doc.qt.io/qt-5.8/statemachine-api.html