我的QThread完成了,但我无法得到信号
My QThread finished but I cannot get the signal
我的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"消息
代码中发生了什么:
- create
QApplication
- create
ThreadTester
-
运行
ThreadTester::runTests
方法,执行以下操作:- 创建胎面对象
- 连接结果
- 螺纹
- wait for thread…
- 现在线程完成它的工作并发出信号
- 由于您的
connect
使用默认连接方法,插槽调用被安排在尚未启动的事件循环中运行。 线程完成等待线程完成(可能在这里你期待最终结果,但看看后来发生了什么)
-
事件循环开始
- 事件循环执行插槽
ThreadTester::threadFinished
的队列调用 - 事件循环等待下一个事件
相关文章:
- Qt VTK交互风格的信号到小部件
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何在没有信号的情况下从C++执行QML插槽
- 线程之间的布尔停止信号
- QThread信号发射不连接
- 如何在Qt中向QThread类的特定对象发出信号
- QThread中的插槽和信号
- 从QThread循环中发射信号
- 为什么QThread::完成信号没有发出
- qthread pharther()信号永远不会发出
- 通过信号/插槽机制将 QString 传递给 QThread
- 在 QThread 中运行长时间操作并将信号发送到主线程仍会冻结 UI
- 无法在多个 Qthread的 QThread 和 finish() 信号之间连接
- QTcpSocket的QThread不发出完成的信号
- Qt信号发射和QThread执行流程
- 带有插槽和信号的QThread似乎不会创建新的线程
- QThread发出finished()信号,但isRunning()返回true, isFinished()返回fals
- 我的QThread完成了,但我无法得到信号
- 如何在QThread中正确处理来自长时间运行的任务的信号和事件