How to sleep/pause in Qt? [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-25 11:53:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!