Reprinted: https://blog.csdn.net/qq_27278957/article/details/106018649 How to use the QThread class
There are two ways to use QThread:
QObject::moveToThread
Method 1 Description:
Define a worker class that inherits from QObject, and define a slot function doWork() in the worker class. This function defines the work that the thread needs to do;
in the controller class to use the thread, create a new QThread object and a worker class object , use the moveToThread() method to hand over the event loop of the worker object to the QThread object for processing;
establish the relevant signal function and slot function to connect, and then send a signal to trigger the QThread slot function to execute the work.
head File
class CopyJudgementData : public QObject
{
Q_OBJECT
public:
explicit CopyJudgementData(QObject *parent = nullptr);
void doWork();
signals:
public slots:
};
CPP
CopyJudgementData::CopyJudgementData(QObject *parent) : QObject(parent)
{
}
void CopyJudgementData::doWork()
{
}
//transfer
pCopyJudgementData=new CopyJudgementData();
pCopyJudgementData->moveToThread(&m_Thread);
connect(ui->action_CopyJudgeData,&QAction::triggered,pCopyJudgementData,&CopyJudgementData::doWork,Qt::QueuedConnection);
//当线程结束时,释放数据处理类
connect(&m_Thread,&QThread::finished,pCopyJudgementData,&CopyJudgementData::deleteLater);
//开启数据处理线程
m_Thread.start();
emit ui->action_CopyJudgeData->triggered();
Inheriting the QThread class
Method 2 description
Customize a class CopyDataThread that inherits QThread, overload the run() function in CopyDataThread, and write the work to be performed in the run() function;
call the start() function to start the thread.
head File
class CopyDataThread : public QThread
{
Q_OBJECT
public:
explicit CopyDataThread(QObject *parent = nullptr);
QMap<QString,QString> map_ConfigInfo;
protected:
void run() override;
signals:
void SNcopyFinish(QString getSN,QString csvpath,int SideFlag,QString SNtxtFilePath);
public slots:
};
CPP
CopyDataThread::CopyDataThread(QObject *parent)
{
}
void CopyDataThread::run()
{
}
//transfer
pCopyDataThread=new CopyDataThread();
pCopyDataThread->start();