0

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!");
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Scott
  • 147
  • 1
  • 4
  • 11
  • 1
    Qt code should never have to wait ideally. What about you use a `signal` when the `Tablet` is connected and react on that signal? – arne Sep 12 '13 at 12:22
  • You could use [QApplication::processEvents()](http://qt-project.org/doc/qt-5.0/qtcore/qcoreapplication.html#processEvents) but it can cause all sorts of trouble. Or you can create a QEventLoop object and call exec. But I would rather do what arne suggested and use a signal/slot method. Or put your code in a separate thread like M M suggested. – thuga Sep 12 '13 at 12:25

2 Answers2

3

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 
    }
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
0

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.

Elvis Dukaj
  • 7,142
  • 12
  • 43
  • 85