我想知道是否有任何方法可以终止等待/延迟条件。
我正在使用QTest::qwait(ms)
在我的代码中添加响应延迟。现在我想终止/打破这个延迟。比如,QTest::qWait(2000)
会延迟 2 秒,那么我应该怎么做才能终止这 2 秒的等待时间?
注意:QTimer
不适合我的代码,我正在使用Qtest:qwait
添加延迟。
简单的答案:你不能。问题是即使您使用 QTimer,假设 QTimer 的超时应该停止等待时间,您会将超时信号连接到什么?或者连接的超时槽会执行什么,或者它会调用哪个函数来停止等待?
最好的办法是使用静态方法QThread::currentThread
获取指向当前QThread的指针,然后您可以使用该指针在 using 上施加等待条件QThread::wait(2000)
,然后您可以使用外部线程在某个条件下停止它。让我们举个例子,您希望线程等待 2 秒或直到进程增加到计数器直到 9999999999。在这种情况下,首先您需要创建自己的类,然后在代码中使用它:
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();
}
在您的实施中:
QThread* thread = QThread::currentThread();
StopThread stopThread(thread);
stopThread->exec();
thread->wait(2000);
我知道您需要使用测试方法来执行此操作,但就我而言,我想不出其他方法。希望能帮助到你 :)