我的 QThread 的运行方法正在完成,但我无法获得信号。
以下是整个代码:
我的主题标题:
#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 ?
注意:&#34;线程已完成&#34;消息正在出现,但是&#34; TEST&#34;消息没有。
答案 0 :(得分:0)
您的代码中会发生什么:
QApplication
ThreadTester
运行方法ThreadTester::runTests
,其执行以下操作:
connect
使用了默认连接方法,因此将调度插槽调用在尚未启动的事件循环中运行。事件循环已启动
ThreadTester::threadFinished