自定义信号与槽

Qt多线程简单实现

多线程间变量传递

工程结构

主线程类:

//export_key.h#ifndefEXPORT_KEY_H#defineEXPORT_KEY_H#include"main_widget.h"namespaceUi{classexport_key;}classtexport_work;classexport_key:publicQWidget{Q_OBJECTpublic:explicitexport_key(QWidget*parent=0);~export_key();publicslots:intsend_cmd(int*len,uchar*pk);private:Ui::export_key*ui;//工作线程对象指针,在类实现中new对象work_threadtexport_work*work_thread;ucharcmd[1024];ucharkek[16];};#endif//EXPORT_KEY_H12345678910111213141516171819202122232425262728291234567891011121314151617181920212223242526272829

//export_key.cpp#include"export_key.h"#include"ui_export_key.h"#include<QMessageBox>//#defineprintpkexport_key::export_key(QWidget*parent):QWidget(parent),ui(newUi::export_key){ui->setupUi(this);//实例化工作线程的对象**work_thread=newtexport_work();**//连接主线程和工作线程,信号处于工作线程,槽位于当前主线程,注意保持信号和槽的参数一致!//connect的第五个参数必须为阻塞队列连接,这样才能保证信号传递过来的参数和槽接收的是实时的!**connect(work_thread,SIGNAL(send_export_signal(int*,uchar*)),this,SLOT(send_cmd(int*,uchar*)),Qt::BlockingQueuedConnection);**}//槽的实现intexport_key::send_cmd(int*len,uchar*pk){work_thread->stop();//接收来自工作线程信号传递过来的参数mymemcpy(cmd,pk,*len);#ifdefprintpkintn=0;ucharcmd2[2048]={0};n=hextostr(cmd,*len,cmd2);cmd2[n]='\0';qDebug("sendpk:%s\n",cmd2);#endifui->pbenter->setEnabled(true);returnErrCode_NoErr;}export_key::~export_key(){deleteui;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454612345678910111213141516171819202122232425262728293031323334353637383940414243444546

工作线程类:

#ifndefEXPORT_WORK_H#defineEXPORT_WORK_H#include<QThread>#include"main_widget.h"//继承Qthread基类,重写虚函数runclasstexport_work:publicQThread{Q_OBJECTpublic:texport_work();protected:voidrun();//自定义信号**signals:voidsend_export_signal(int*,uchar*);**private:volatileintstart_export;};#endif//EXPORT_WORK_H12345678910111213141516171819202122232425261234567891011121314151617181920212223242526

//export_work.cpp#include"export_work.h"#include"export_key.h"#include<QThread>texport_work::texport_work(){start_export=0;}//重写虚函数run,在虚函数中实现要在工作线程中要做的事情,开启事件循环voidtexport_work::run(){while(!start_export){qDebug()<<"startthread!";timerThread();//自定义函数}start_export=0;}voidtexport_work::stop(){start_export=1;}voidtexport_work::timerThread(){intlen=0;ucharbuf[1024];len=serial::GetSerialPtr()->recvcommdata(buf);if(len<=0)return;if(buf[0]==0xAA){if(buf[1]||buf[2]||buf[3]||buf[4]!=16)return;//发射信号,自定义信号send_export_signal并将变量len和数组buf传递给槽函数。emitsend_export_signal(&len,buf);}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849501234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950

总结:
1.跨线程连接信号与槽时注意连接方式,也就是connect函数第五个参数
2.实现多线程方式,工作线程继承Qthread基类,重写虚函数run在run中实现工作线程需要做的事情;在主线程中创建工作线程的实例,可以对工作线程进行控制。
3.多线程间传递变量的一种是直接通过信号与槽的连接实现,注意连接方式