我的QThread完成了,但我无法得到信号

My QThread finished but I cannot get the signal

本文关键字:信号 QThread 我的      更新时间:2023-10-16

我的QThread的run方法正在结束,但是我无法获得信号

完整代码如下:

我的线程头:

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
#include "mydataobject.h"
class MyThread: public QThread
{
    Q_OBJECT
public:
    MyThread(MyDataObject data,
             bool useData);
private:
    void run();
signals:
    void resultsReady(MyDataObject data);
private:
    MyDataObject data;
    bool useData;
};
#endif // MYTHREAD_H
我的线程代码:
#include "mythread.h"
MyThread::MyThread(MyDataObject data, bool useData)
{
    this->data = data;
    this->useData = useData;
}
void MyThread::run()
{
    if( useData )
    {
        data.calculate(); // Do something
    }
    emit resultsReady(data);
    qDebug() << "Thread finished";
}

我的测试头:

#ifndef THREADTESTER_H
#define THREADTESTER_H
#include <QDebug>
#include "mythread.h"
class ThreadTester: public QObject
{
    Q_OBJECT
public:
    ThreadTester();
    void runTests();
public slots:
    void threadFinished(MyDataObject data);
private:
    MyDataObject data;
};
#endif // THREADTESTER_H
我的测试代码:
#include "threadtester.h"
ThreadTester::ThreadTester(){}
void ThreadTester::runTests()
{
    qRegisterMetaType<MyDataObject>("MyDataObject");
    MyDataObject data;
    MyThread* thread = new MyThread(data, true);
    connect(thread, SIGNAL(resultsReady(MyDataObject)),
            this, SLOT(threadFinished(MyDataObject)));
    thread->start();
    thread->wait();
}
void ThreadTester::threadFinished(MyDataObject data)
{
    qDebug() << "TEST";
    this->data = data;
}

主要功能:

#include <QApplication>
#include "threadtester.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ThreadTester threadTester;
    threadTester.runTests();
    return a.exec();
}
为什么从来不调用公共槽位threadFinished ?

注意:出现了"Thread finished"消息,但没有出现"TEST"消息

代码中发生了什么:

  1. create QApplication
  2. create ThreadTester
  3. 运行ThreadTester::runTests方法,执行以下操作:

    • 创建胎面对象
    • 连接结果
    • 螺纹
    • wait for thread…
    • 现在线程完成它的工作并发出信号
    • 由于您的connect使用默认连接方法,插槽调用被安排在尚未启动的事件循环中运行。
    • 线程完成
    • 等待线程完成(可能在这里你期待最终结果,但看看后来发生了什么)
  4. 事件循环开始

  5. 事件循环执行插槽ThreadTester::threadFinished的队列调用
  6. 事件循环等待下一个事件