QT在項目使用過程中建立了一個線程,由于線程中run還是中處理有自己想要處理的業務邏輯,想在啟用一個線程或者定時器去做别的事情,如果不使用信号槽的情況下使用線程是不存在問題的
#ifndef MONITORTHREAD_H
#define MONITORTHREAD_H
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QTimer>
class WorkerSubThread: public QThread
{
public:
WorkerSubThread() { }
virtual void run()
{
qDebug() << "run thread";
}
};
class MonitorThread : public QThread
{
public:
MonitorThread();
~MonitorThread();
protected:
void run();
WorkerSubThread *m_pSubThread;
QTimer * m_pTimer;
//public slots:
// void ExecThread();
private:
bool m_bStop;
};
#endif // MONITORTHREAD_H
#include "MonitorThread.h"
MonitorThread::MonitorThread()
{
m_pSubThread = new WorkerSubThread;
m_pSubThread->start();
m_pTimer = new QTimer();
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(ExecThread()));
m_pTimer->start(500);
m_bStop = false;
}
MonitorThread::~MonitorThread()
{
m_bStop = true;
}
void MonitorThread::run()
{
while(!m_bStop)
{
// m_pSubThread = new WorkerSubThread;
// m_pSubThread->run();
qDebug() << "run bussiness logic";
//進行相關操作
msleep(100);
}
}
void MonitorThread::ExecThread()
{
if (m_pSubThread != 0)
m_pSubThread->start();
}
如果使用信号槽的話需要添加Q_OBJECT宏用于此時由于将無法使用線上程中使用線程了,會報錯誤資訊,無法連接配接相關的線程類。解決方法就是不使用定時器和信号槽了