QThread中含有一个run()函数,它是线程的入口点。其在QThread类中的声明如下:
protected:
virtual void run();
所以不能直接调用run()来启动线程,而是通过调用QThread的start()方法来启动线程。当调用来start()后,run()就会被执行。QThread类中对run()的默认实现只是在函数体内调用了exec()函数而已,所以要让子线程完成特定的功能,需要通过继承QThread,然后重新实现run()来完成。或者也可以自定义一个对象,然后将这个对象移动到子线程中来实现。下面来分别讨论这两种做法。
1.通过QThread的子类来使用子线程
如:
#include <QThread>
#include <QDebug>
// 子线程类
class WorkerThread : public QThread
{
Q_OBJECT
public:
explicit WorkerThread(QObject *parent = nullptr): QThread(parent)
{
qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread constructor";
}
void run()
{
qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread result ready";
emit resultReady();
this->exec(); // 用于启动event loop,这时子线程会一直存在。除非手动调用quit()函数。如果没有这行语句,run()函数执行完返回后,就会触发子线程的finished信号。
}
void share()
{
qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread share method";
}
public slots:
void todo() // 这是子线程中用于处理其他线程的信号的槽函数
{
qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread goon";
QThread::sleep(10);
qDebug() << "thread i