QTimer在线程中-事件未处理? [英] QTimer in a thread - events not processing?
问题描述
我有一个从QThread派生的对象,并且类定义包括Q_OBJECT宏.我在线程中创建了一个计时器,因此我可以在线程运行时偶尔进行一些检查.但是,超时事件从未发生.
I have an object that is derived from QThread and the class definition includes the Q_OBJECT macro. I created a timer within the thread so I can do some occasional checks while the thread is running; however, the timeout event is never occurring.
我也尝试过将计时器设置为单发,但是没有发出任何事件.
I've tried making the timer a singleshot as well, but no events are emitted.
默认情况下,事件是否在线程中处理吗?或者我需要做其他事情来处理它们吗?
Are events processed in a thread by default or do I need to do something else to have them processed?
以下是我如何设置线程和计时器的代码:
Here's the code for how I set up the thread and timers:
void MyClass::run( void )
{
checkTimer_chA = new QTimer( this );
qDebug() << connect( checkTimer_chA, SIGNAL( timeout() ), this, SLOT( timerExpiry_chA() ) );
checkTimer_chA->start( 1000 );
// prevent multiple, simultaneous starts
if( !isRunning )
{
qDebug() << "Thread: MyClass::run";
isRunning = true;
while( isRunning )
{
getData();
processData();
yieldCurrentThread();
}
}
checkTimer_chA->stop();
delete checkTimer_chA;
}
void DAQ::timerExpiry_chA( void )
{
qDebug() << "timerExpiry_chA";
checkTimer_chA->stop();
}
如果我在调用 yieldCurrentThread(); 之前添加 QApplication :: processEvents(); ,计时器将按预期工作.但是,这对我来说似乎是错误的.
If I add QApplication::processEvents(); right before the call to yieldCurrentThread(); the timer works as expected. However, this seems wrong to me.
推荐答案
除非您在线程中显式创建事件循环,否则线程没有它们自己的事件循环.请参见 http://doc.qt.io /qt-5/threads-qobject.html#per-thread-event-loop 了解详情.
Threads do not have their own event loops unless you explicitly create event loops in them. See http://doc.qt.io/qt-5/threads-qobject.html#per-thread-event-loop for details.
这篇关于QTimer在线程中-事件未处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!