gpt4 book ai didi

线程中的 QTimer - 事件未处理?

转载 作者:行者123 更新时间:2023-12-04 13:06:08 28 4
gpt4 key购买 nike

我有一个派生自 QThread 的对象,类定义包括 Q_OBJECT 宏。我在线程中创建了一个计时器,这样我就可以在线程运行时进行一些偶尔的检查;但是,超时事件永远不会发生。

我也试过将计时器设置为单次触发,但没有发出任何事件。

默认情况下,事件是在线程中处理的,还是我需要做其他事情来处理它们?

这是我如何设置线程和计时器的代码:

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();,计时器将按预期工作。但是,这对我来说似乎是错误的。

最佳答案

在 Qt 中使用线程有时会有点麻烦。 This博文让我大开眼界。如果我们采用博客文章中提出的风格来解决您的问题,我们最终会得到如下所示的解决方案。

Consumer::Consumer():
checkTimer_(new QTimer(this))
{
QObject::connect(checkTimer_, SIGNAL(timeout()), this, SLOT(onTimerExpiration());
QObject::connect(this, SIGNAL(ready()), this, SLOT(consume());
}

bool Consumer::event(QEvent *e)
{
if (e->type() == QEvent::ThreadChange)
{
QTimer::singleShot(0, this, SLOT(start());
}

return QObject::event(e);
}

void Consumer::consume()
{
getData();
processData();
emit ready();
}

void Consumer::start()
{
checkTimer_->start(1000);
emit ready();
}

void Consumer::onTimerExpiration()
{
qDebug() << "timeout";
}

然后在单独的线程中运行如下:

...
Consumer *consumer = new Consumer();
...
QThread *thread = new QThread(this);
thread->start();
consumer->moveToThread(thread);

Consumer 的所有子对象将在 Consumer 移动到的线程的上下文中运行。可以为 Consumer 类创建超时信号,并将其与未在 thread 中运行的对象连接。一旦对象移动到线程,Qt 将确保将正确的信号/槽类型应用于连接。

我省略了整个 isRunning 部分,因为我怀疑只要您只创建一个 Consumer,您仍然需要它。

关于线程中的 QTimer - 事件未处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374034/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com