自定义信号与槽
Qt多线程简单实现
多线程间变量传递
工程结构
主线程类:
//export_key.h#ifndef EXPORT_KEY_H#define EXPORT_KEY_H#include "main_widget.h"namespace Ui {class export_key;}class texport_work;class export_key : public QWidget{ Q_OBJECTpublic: explicit export_key(QWidget *parent = 0); ~export_key();public slots: int send_cmd(int *len, uchar *pk);private: Ui::export_key *ui; //工作线程对象指针,在类实现中new对象work_thread texport_work *work_thread; uchar cmd[1024]; uchar kek[16];};#endif // EXPORT_KEY_H12345678910111213141516171819202122232425262728291234567891011121314151617181920212223242526272829
//export_key.cpp#include "export_key.h"#include "ui_export_key.h"#include//#define printpkexport_key::export_key(QWidget *parent) : QWidget(parent), ui(new Ui::export_key){ ui->setupUi(this); //实例化 工作线程的对象 **work_thread = new texport_work();** //连接主线程和工作线程,信号处于工作线程,槽位于当前主线程,注意保持信号和槽的参数一致! //connect的第五个参数必须为阻塞队列连接,这样才能保证信号传递过来的参数和槽接收的是实时的! **connect(work_thread,SIGNAL(send_export_signal(int *,uchar *)),this,SLOT(send_cmd(int *,uchar*)),Qt::BlockingQueuedConnection);**}//槽的实现int export_key::send_cmd(int *len,uchar* pk){ work_thread->stop(); //接收来自工作线程信号传递过来的参数 mymemcpy(cmd,pk,*len);#ifdef printpk int n = 0; uchar cmd2[2048] = {0}; n = hextostr(cmd,*len,cmd2); cmd2[n] = '\0'; qDebug("send pk:%s \n",cmd2);#endif ui->pbenter->setEnabled(true); return ErrCode_NoErr;}export_key::~export_key(){ delete ui;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454612345678910111213141516171819202122232425262728293031323334353637383940414243444546
工作线程类:
#ifndef EXPORT_WORK_H#define EXPORT_WORK_H#include#include "main_widget.h"//继承Qthread基类,重写虚函数runclass texport_work : public QThread{ Q_OBJECTpublic: texport_work();protected: void run();//自定义信号**signals: void send_export_signal(int *,uchar *);**private: volatile int start_export; };#endif // EXPORT_WORK_H12345678910111213141516171819202122232425261234567891011121314151617181920212223242526
//export_work.cpp#include "export_work.h"#include "export_key.h"#includetexport_work::texport_work(){ start_export = 0;}//重写虚函数run,在虚函数中实现要在工作线程中要做的事情,开启事件循环void texport_work::run(){ while(!start_export) { qDebug()<<"start thread!"; timerThread();//自定义函数 } start_export = 0;}void texport_work::stop(){ start_export = 1;}void texport_work::timerThread(){ int len = 0; uchar buf[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传递给槽函数。 emit send_export_signal(&len,buf); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849501234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
总结:
1.跨线程连接信号与槽时注意连接方式,也就是connect函数第五个参数 2.实现多线程方式,工作线程继承Qthread基类,重写虚函数run在run中实现工作线程需要做的事情;在主线程中创建工作线程的实例,可以对工作线程进行控制。 3.多线程间传递变量的一种是直接通过信号与槽的连接实现,注意连接方式