天天看点

Qt使用moveToThread()

背景:有一个自定义任务类,需要在线程中完成特定任务,但是又不想继承QThread,重写run()的方式使用。

自定义一个任务类,此类需要继承QObject类:

class Task:public QObject
{
    Q_OBJECT
public:
    Task();
    ~Task();
public slots:
    void doWork();
signals:
    void workFinished();
};
           

然后在需要使用的地方进行实例化及moveToThread操作:

QThread *m_pThread = new QThread();
    Task *m_pTask = new Task();
    m_pTask->moveToThread(m_pThread);
    connect(m_pThread, &QThread::started, m_pTask, &Task::doWork);
    connect(m_pTask, &Task::workFinished, m_pThread, &QThread::quit);
    connect(m_pThread, &QThread::finished, m_pTask, &Task::deleteLater);
    connect(m_pThread, &QThread::finished, m_pThread, &QThread::deleteLater);
           

quit()方法不能少,否则会出现crash。

.h
QThread *actionLoop;

.cpp
actionLoop = new QThread();
actionLoop->setObejectName("actionLoop");
actionLoop->start();

this->moveToThread(actionLoop);
           

继续阅读