我希望我的程序等待QTimer超时来执行特定的方法。该函数在一个循环中执行一些计算,在该循环结束后,它应该等待计时器超时,并在计时器事件结束后再次运行。
下面是生成线程并将计时器连接到generateData()方法的代码的当前状态。此代码在Class的构造函数中执行。
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循环后等待计时器。
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似乎不会停止该方法在该时间内的执行。有没有其他方法可以做到这一点?
发布于 2018-06-28 16:53:37
你的方法看起来不必要的复杂。我会做以下事情:
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循环,因为计时器递归地调用相同的函数。
发布于 2018-06-28 17:16:20
结合你在其他答案上给出的提示,我认为这就是你想要的:
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
https://stackoverflow.com/questions/51078390
复制相似问题