QTimer->remainingTime() 返回 -1371648957
QTimer->remainingTime() returns -1371648957
当我使用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之后和请求剩余时间之前返回到主事件循环。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- QTimer->remainingTime() 返回 -1371648957