然后把要实现的函数写在这个类里,在run函数中调用。在需要开辟线程的地方,new一个线程类出来,通过线程的start函数运行线程,回自动执行run函数。
例如:
线程类
class Thread : public BaseThread
{
Q_OBJECT
public:
explicit Thread (QObject *parent = Q_NULLPTR);
~Thread ();
void checkSceneFile(GraphicsScene *scene);
protected:
void run();
private:
GraphicsScene *_scene {Q_NULLPTR};
};
Thread::CheckThread(QObject *parent) :BaseThread(parent)
{
}
Thread::~CheckThread()
{
}
void Thread::checkSceneFile(GraphicsScene *scene)
{
/*** 实现的功能 ***/
}
void Thread::run()
{
checkSceneFile(_scene);
}
调用线程
A文件头文件中定义线程
private:
Thread* _thread {Q_NULLPTR};
=============================================================
A文件cpp中调用线程
void A::init(){
//已存在就删除原来的线程
if(_thread ){
if( _thread->isRunning()){
delete _thread ;
_thread = Q_NULLPTR;
}
}
_thread = new Thread(this);
/** 中间也可以在线程类中自定义一些传数据的函数 然后在这里传入数据 **/
_thread ->start();
}
void A::~A(){
//释放
_thread ->blockSignals(true);
delete _thread ;
_thread = Q_NULLPTR;
}
//在BlockFileTreeView文件中,调用importlotsFile函数,传入importlotsFile函数需要的参数importFiles
QFuture f1 = QtConcurrent::run(this,&A::importlotsFile,importFiles);
f1.waitForFinished();
【注意】waitForFinished不是并行的,是会阻塞主线程的。
但是,我又不想要阻塞主线程,还能指定线程结束后执行什么,要怎么做?
我的做法是 利用信号槽 。
在线程掉用的importlotsFile函数结束的时候发送一个信号,然后在主函数接收这个信号。这样就可以不用阻塞主线程,能知道子线程结束。