首页 文章

QThread向GUI接收信号,但不是异步响应

提问于
浏览
0

我在QObject派生类下进行了大量计算 . 我通过GUI中的按钮将其移动到我的新qthread,它只是为了执行该计算而创建的 .

GUI应该在循环中等待来自工作线程的消息(因为在执行按钮槽之后,它就会去那里) .

我通过信号和插槽机制发出消息,如下所示 . 我有一个泛型类Controller,它执行线程的创建并将其与GUI(MainWindow)连接:

QThread* thread = new QThread;
Raytracer* worker = new Raytracer();
worker->moveToThread(thread);

QObject::connect(thread, &QThread::started, worker, &Raytracer::execute);//, Qt::QueuedConnection);
QObject::connect(worker, &Raytracer::textEmitted, gui_, &MainWindow::addText, Qt::QueuedConnection);
QObject::connect(worker, &Raytracer::hitEmitted, gui_, &MainWindow::hitReceived, Qt::QueuedConnection);
QObject::connect(worker, &Raytracer::finished, worker, &Raytracer::deleteLater, Qt::QueuedConnection);
QObject::connect(worker, &Raytracer::finished, thread, &QThread::quit, Qt::QueuedConnection);
QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater, Qt::QueuedConnection);
QObject::connect(thread, &QThread::finished, this, &MainController::finishedCalculation, Qt::QueuedConnection);


thread->start();

关于Raytracer类:

class Raytracer : public QObject
{
Q_OBJECT

在计算过程中,它会发出如下内容:

emit textEmitted(QString("Number %1\n").arg(number));

GUI接收信号:

void addText(const QString& text) { outputBox_->append( text ); }

接收信号并将其正确添加到GUI中的文本框中 . But they appear just after the thread finished . 不计算期间,无论多长时间 .

所有消息都已收到 . 因此,它有点将它们保存在某个缓冲区中并在最后更新文本 .

What am i doing wrong and in which situations this could happen? How could it test it?

1 回答

  • 1

    GUI线程被其他东西阻止,或者你的其他线程在工作时没有发出信号,但仅在最后 . 您没有显示足够的代码来诊断错误 .

    我有a stand-alone example几乎可以做你正在做的事情 . 唯一需要的更改是在 runTestemit 之后)的末尾添加 QThread::msleep(1000); . 这将近似于需要1秒才能执行的测试 .

相关问题