问题
How do I "Sleep/Pause" inside Qt.
I want the UI to remain responsive while the code is sleeping.
while(Tablet.IsConnected() == false){
LogText("[Prep] Tablet not turned back on... Retrying...");
//Sleep for three seconds here
}
LogText("[Prep] Tablet Detected!");
回答1:
let tablet emit a signal:
in your constructor you will then do:
connect(Tablet, SIGNAL(connected()), this, SLOT(onConnected());
and then do your processing in
slots:
void connected()
{
LogText("[Prep] Tablet Detected!");
}
if there is no signal available (third party library) then you can use a QTimer to repeatedly check:
class MyClass:public QObject
{
Q_OBJECT
QTimer timer;
Tablet tablet;
public:
MyClass(QObject * parent = 0) : QObject(parent)
{
connect(&timer, SIGNAL(timeout()), SLOT(connected());
timer.setSingleShot(false);
timer.setInterval(3000);
timer.start();
}
Q_SLOT void connected()
{
if (!tablet.isConnected())
{
LogText("[Prep] Tablet not turned back on... Retrying...");
return;//wait for next timeout from the timer
}
LogText("[Prep] Tablet Detected!");
timer.stop();
//do some processing
}
}
回答2:
Is not a good idea have long operation in the GUI Thread. You have to create another thread for long task (or a thread pool). See std::thread
or QTThread
. Or even std::async
.
来源:https://stackoverflow.com/questions/18764094/how-to-sleep-pause-in-qt