Qt中有两种实现多线程的方式,其中一种是写一个继承于Object的类,将这个类移入QThread 对象中,代码如下:
1.写一个继承于object 的线程类
//头文件
class executorThread : public QObject
{
Q_OBJECT
public:
executorThread(QObject *parent=0);
~executorThread();
//源文件
executorThread::executorThread(QObject *parent)
: QObject(parent)
{
}
executorThread::~executorThread()
{
}
2.主线程中将开辟的线程类移入QThread 对象中
m_objThread = new QThread();
m_ThreadTwo = new executorThread();//需要执行的线程类
m_ThreadTwo->moveToThread(m_objThread);//将线程类移入QThread对象中
connect(m_objThread, &QThread::finished, m_objThread, &QObject::deleteLater);
connect(this, &AutoTestUi::sig_start, m_ThreadTwo, &executorThread::test);//子线程中需要执行的操作都放入test函数中
connect(m_ThreadTwo, &executorThread::sig_showExample, this, &AutoTestUi::slot_showExample);
connect(m_ThreadTwo, &executorThread::sig_showResult, this, &AutoTestUi::slot_showResult);
connect(m_ThreadTwo, &executorThread::sig_identifyResult, this, &AutoTestUi::slot_identifyResult);
m_objThread->start();//线程开始
emit sig_start(m_filePath,m_box);//将数据传递给子线程
3.子线程暂停和恢复
void executorThread::pauseThread(bool status)
{ //设置线程锁的标志位
if (status)
{
QMutex m_lock.lock();//暂停
}
else
{
QMutex m_lock.unlock();//恢复
}
}
void executorThread::test(const QStringList& fileName, const QVector<QStandardItem*> m_box)
{
foreach(auto step, stepList)
{
QMutexLocker locker(&m_lock);//这里通过线程锁的标志位来判断线程是暂停还是运行
resOk = true;
exeDis.clear();
eveOk = exep->exeCmd(step.second, resOk, exeDis);
emit sig_showResult(stepList,step, eveOk,exeDis);
// 对执行结果 处理, 打印, 保存
// todo
}
}