如何终止延迟/等待条件

时间:2011-02-22 13:30:44

标签: qt qtestlib

我想知道是否有任何方法可以终止等待/延迟条件。

我正在使用QTest::qwait(ms)在我的代码中添加响应延迟。现在我想终止/打破这种延迟。像QTest::qWait(2000)这样的东西会延迟2秒,那么我应该怎样做才能终止这2秒的等待时间呢?

注意:QTimer不适合我的代码,我使用Qtest:qwait来添加延迟。

1 个答案:

答案 0 :(得分:1)

简单的答案:你做不到。问题是即使你使用QTimer,并且假设QTimer的超时应该停止等待时间,你将超时信号连接到什么?或者连接的超时时隙会执行什么,或者它会调用哪个函数来停止等待?

您最好的选择是使用静态方法QThread::currentThread获取指向当前 QThread 的指针,然后您可以使用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);

我知道你需要用测试方法做到这一点,但就我而言,我想不出另一种方式。希望它有所帮助:)