QThread: Destroyed while thread is still running的处理方法
如果把一个基于QObject的类的槽运行在另一个线程,我们可以用moveToThread的方法。但在使用过程中,退出程序时会报上面的错误。在网上找了一些方法,但总感觉不太合适。
现在解决思路如下:
线程类:
class WorkerThread : public QThread
{
Q_OBJECT
public:
WorkerThread(QObject *parent = Q_NULLPTR) :
QThread(parent)
{
}
~WorkerThread()
{
quit();
wait();
}
};
具体需要多线程执行槽的类:
内含WorkerThread对象,该类的槽处理在WorkerThread对象中,实现多线程。而且有比较好的封装。
class MyClass: public QObject
{
Q_OBJECT
public:
MyClass() : QObject()
{
moveToThread(&worker);
worker.start();
}
public slots:
void testSlots()
{
qDebug() << "at" << __FUNCTION__;
}
private:
WorkerThread worker;
};