The simple answer: You can't. The problem is that even if you use QTimer, and let's say a timeout of the QTimer is supposed to stop the waiting time, what would you connect your timeout signal to? Or what would a connected timeout slot execute or which function would it call to stop the wait?
Your best bet is to use the static method QThread::currentThread
to obtain a pointer to the current QThread which you can then use to impose a wait condition on by using QThread::wait(2000)
and then you can use an external thread to stop it on a condition. Let's take an example where in you want a thread to wait for 2s or till a processes increments to a counter till 9999999999. In that case, first you need to create your own class and then use it in your code:
class StopThread : public QThread {
private:
QThread* _thread;
public:
StopThread(QThread*);
void run();
};
StopThread::StopThread(QThread* thread) {
_thread = thread;
}
void StopThread::run() {
//Do stuff here and see when a condition arises
//for a thread to be stopped
int i = 0;
while(++i != 9999999999);
_thread->quit();
}
And in your implementation:
QThread* thread = QThread::currentThread();
StopThread stopThread(thread);
stopThread->exec();
thread->wait(2000);
I understand that you need to do this with the testing method, but as far as I go, I can't think of another way. Hope it helps :)