首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用QTimer和Eventloop延迟代码执行

使用QTimer和Eventloop延迟代码执行
EN

Stack Overflow用户
提问于 2018-06-28 16:41:52
回答 2查看 1.5K关注 0票数 0

我希望我的程序等待QTimer超时来执行特定的方法。该函数在一个循环中执行一些计算,在该循环结束后,它应该等待计时器超时,并在计时器事件结束后再次运行。

下面是生成线程并将计时器连接到generateData()方法的代码的当前状态。此代码在Class的构造函数中执行。

代码语言:javascript
复制
timer = new QTimer(0);
timer->setTimerType(Qt::PreciseTimer);
timer->setInterval(40); //25 frames per second


QThread *thread = new QThread(this);
moveToThread(thread);
timer->moveToThread(thread);

connect(thread, SIGNAL(started()), timer, SLOT(start()));
connect(timer, SIGNAL(timeout()), this, SLOT(timerEvent()));
connect(thread, SIGNAL(started()), this, SLOT(generateData()));
connect(this, SIGNAL(finished()), thread, SLOT(quit()));

thread->start();

方法,该方法应在执行for循环后等待计时器。

代码语言:javascript
复制
void Class::generateData() {
    while (1) {
        calculation()
        //do some calculation, which takes around 3-5ms
        QEventLoop loop;
        connect(timer, SIGNAL(timeout()), &loop, SLOT(quit()));
        loop.exec();
    }
}

eventloop似乎不会停止该方法在该时间内的执行。有没有其他方法可以做到这一点?

EN

回答 2

Stack Overflow用户

发布于 2018-06-28 16:53:37

你的方法看起来不必要的复杂。我会做以下事情:

代码语言:javascript
复制
void Class::generateData()
{
    // Do calculations.
    for (int i = 0; i<object1->size(); ++i)
    {
      object1->at(i)->test();
    }
    // Wait a little bit and do calculations again.
    QTimer::singleShot(40, this, SLOT(generateData()));
}

注意,我去掉了while循环,因为计时器递归地调用相同的函数。

票数 0
EN

Stack Overflow用户

发布于 2018-06-28 17:16:20

结合你在其他答案上给出的提示,我认为这就是你想要的:

代码语言:javascript
复制
Class::Class(QObject *parent)
{
    timer = new QTimer(0);
    timer->setTimerType(Qt::PreciseTimer);
    timer->setInterval(40); //25 frames per second

    QThread *thread = new QThread(this);
    moveToThread(thread);
    timer->moveToThread(thread);
    this->moveToThread(thread);

    connect(thread, SIGNAL(started()), timer, SLOT(start()));
    connect(timer, SIGNAL(timeout()), this, SLOT(generateData()));
    connect(this, SIGNAL(finished()), timer, SLOT(stop()));
    connect(this, SIGNAL(finished()), thread, SLOT(quit()));

    thread->start();
}

void Class::generateData()
{
    // Do calculations.
    for (int i = 0; i<object1->size(); ++i)
    {
        object1->at(i)->test();
    }
}

每次计时器超时时,它都会触发线程上的generateData函数(因为您已将类移至该线程)。计时器将保持25 Hz的脉冲,因为它实际上是一个系统调用(而不是该线程上的活动等待)。在Windows上,它可能不够准确。

请注意,如果它有父类,则不能对其调用moveToThread,请参阅QT docs另请注意,类应该从QObject派生,但我认为已经是这种情况,因为您正在connecting

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51078390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档