"QObject::startTimer: timers cannot be started from another thread"没有计时器和 CPU 消耗

"QObject::startTimer: timers cannot be started from another thread" without timers && CPU consumption

本文关键字:计时器 消耗 CPU thread from startTimer QObject timers cannot started be      更新时间:2023-10-16

我用Qt(4.7.2)创建了一个多线程应用程序。只有主线程有事件循环。

问题是有时我在控制台中得到以下警告:

QObject::startTimer: timers cannot be started from another thread

在此发生后,应用程序消耗100%的CPU(我有一个单核CPU)。看起来,主线程消耗了所有的CPU资源。程序没有冻结,一切仍然工作。

当我在调试器中停止程序时,我在调用堆栈中看不到我的代码。

问题是我根本没有使用(无论如何显式地)计时器。

它可能与什么有关?我知道,这个问题很常见,但我甚至不明白,该显示哪段代码。

谢谢@ vince,我已经解决了这个问题。我使用信号/插槽机制+ Qt::QueuedConnection与GUI通信

例如,如果我需要从工作线程设置QLabel的文本,我可以在我的工作线程信号

void textChanged(QString);

然后使用Qt::QueuedConnection

将此信号连接到QLabel的插槽
connect(worker, SIGNAL(textChanged(QString)), label, SLOT(setText(QString), Qt::QueuedConnection);

如果我想同步执行setText,我可以使用Qt::BlockingQueuedConnection

现在在我的工作线程中,我只是发出信号:

emit textChanged(newText);

也可以使用QMetaObject函数来避免信号和插槽:

metaObject->invokeMethod(label, "setText", Qt::QueuedConnection, Q_ARG(QString, text));

最初令人困惑的几个PyQt"警告"之一;(结果)一个典型原因的症状:试图使用非"应用程序线程"操作GUI元素,而没有使用应该使用的信号和槽。