QTimer->remainingTime() 返回 -1371648957

QTimer->remainingTime() returns -1371648957

本文关键字:返回 -1371648957 remainingTime gt QTimer-      更新时间:2023-10-16

当我使用Qt 5.3.2运行以下代码时,剩余时间设置为-1371648957。

QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(100);
qDebug() << "remaining" << timer->remainingTime();

如果之后我继续打印循环中的剩余时间,负值就会增加,因此timeout()永远不会被激发。这对我来说真的毫无意义。

为了提供一点上下文,此代码在一个单独的线程内运行,并且QTimer不是在线程对象的构造函数中创建的。

下面是一些更新后的代码,让事情变得更清楚。

void MainObject::SomeMethod(){
    // main thread
    ObjectWithTimer *owt = new ObjectWithTimer();    
    QThread *someThread = new QThread();
    owt->moveToThread(someThread);
    connect(someThread, SIGNAL(started()), owt, SLOT(doStuff()));
    someThread->start();
}
void ObjectWithTimer::doStuff(){
    while(condition){
        // do various stuff
        // among other things emit SIGNALS to the main thread, that are received
        // so the event loop in the thread is running
        QTimer *timer = new QTimer(this);
        timer->setSingleShot(true);
        timer->start(100);
        qDebug() << "remaining" << timer->remainingTime();
        connect(timer, SIGNAL(timeout()), this, SLOT(onClientTimeoutTest()));
    }
}
void ObjectWithTimer::onClientTimeoutTest(){
    // this method is of course never fired, since the remaining time never reaches 0
}

我已经检查了定时器创建是否在单独的线程中正确运行,以及线程内的Qts事件循环是否正常工作,因为我可以emit主线程接收的信号。

同样,如果我像一样设置计时器,也没有什么区别

timer->setSingleShot(true);
timer->setInterval(100);
timer->start();

如果我将秒数更改为100000或0,则剩余时间只会略有变化,例如,当我重新启动应用程序时,剩余时间仍会更改为-137402988,但长度保持不变。

此外,我在timer->remainingTime()行上与调试器进行了检查,内部inter变量正确设置为100。

这可能是记忆地址或类似的东西吗?

QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(100);
qDebug() << "remaining" << timer->remainingTime();

由于QTimer在事件循环中工作,我怀疑调用remainingTime此时可能返回无效,因为Timer尚未完全初始化。

如果您遵循QTimer的源代码,您将看到它实际上使用了QObject的计时器并调用QObject::startTimer。QObject的源代码(第1632行)显示了一个事件在这一点上被调度:-

return d->threadData->eventDispatcher->registerTimer(interval, this);

因此,允许代码在调用start之后和请求剩余时间之前返回到主事件循环。