2019年08月18日起笔
方式一:继承QThread重写run函数
MyThread.h ----------------------------------- ... class MyThread : public QThread { protected: void run(); } MyThread.cpp ----------------------------------- ... void MyThread::run() { //do something ... exec(); } Main.cpp ------------------------------------ ... MyThread * myThread = new MyThread; MyThread.start(); ...
方式二:继承QObject并moveToThread
MyWork.h -------------------------------------- class MyWork : public QObject { Q_OBJECT public: explict MyWork(QObject * parent = nullptr); public slots: void slotsDoWork(); }; MyWork.cpp -------------------------------------- MyWork::MyWork(QObject *parent):QObject(parent) {} void MyWork::slotsDoWork() { //do something } someWhere.cpp -------------------------------------- ... QThread * thread = new QThread(this); MyWork * myWork = new MyWork;
QObject::connect(thread, &QThread::started, myWork, &MyWork::slotsDoWork); MyWork->moveToThread(thread); thread->start();
/*
*深入:thread 和 myWork分别在哪个线程中运行? :https://www.cnblogs.com/azbane/p/11465466.html
*/
消息和槽在线程和依附线程间的传递:
首先说明:依附线程是指创建线程的线程。
情况一:线程发射消息,依附线程接收消息
一.1继承QThread重写run函数,小熊尝试失败,针对代码及编译错误消息如下:
MyThread.h --------------------------------- signals: void signalsA(); MyThread.cpp --------------------------------- void MyThread::run() { ... emit signalsA(); ... } 编译错误: --------------------------------- LNK2019:无法解析的外部符号"public: void __thiscall MyThread::signalsA(void)"(?signals@MyThread@@QAEXXZ),该符号在函数 " protected: virtual void __thiscall MyThread::run(void) " (?run@MyThread@@MAEXXZ)中被引用
在run函数中发射消息编译会报错....就不用写关联此信号的槽..了
一.2继承QObject并moveToThread
MyWork.h ------------------------------------ signals: void signalsA(); MyWork.cpp ------------------------------------ void MyWork::slotsDoWork() { ... emit signalsA(); ... } someWhere.cpp ----------------------------------- QObject::connect(myWork, &MyWork::signalsA, this, &someWhere::slotsToDoSomething);
很顺畅,小熊目前没有发现什么问题。
情况二:依附线程发送消息,线程接收消息
暂未使用到,待补充