第一种:继承QThread
#ifndef THREADFROMQTHREAD_H
#define THREADFROMQTHREAD_H
#include <QThread>
#include <QObject>
class ThreadFromQThread : public QThread
{
Q_OBJECT
public:
ThreadFromQThread();
protected:
void run();
};
#endif // THREADFROMQTHREAD_H
#include "threadfromqthread.h"
ThreadFromQThread::ThreadFromQThread()
{
}
void ThreadFromQThread::run()
{
}
实现:
ThreadFromQThread* myThread = new ThreadFromQThread;
myThread.start();
注意:
- 只有
run
函数是在新线程中,必须重写QThread
的run()
函数 run()
是线程执行的入口,通过start()
函数来实现调用的。
第二种:继承QObject
#ifndef THREADFROMQOBJECT_H
#define THREADFROMQOBJECT_H
#include <QObject>
class ThreadFromQObject : public QObject
{
Q_OBJECT
public:
explicit ThreadFromQObject(QObject *parent = nullptr);
public slots:
void runThread();
signals:
};
#endif // THREADFROMQOBJECT_H
#include "threadfromqobject.h"
ThreadFromQObject::ThreadFromQObject(QObject *parent) : QObject(parent)
{
}
void ThreadFromQObject::runThread()
{
}
实现:
QThread * thread = new QThread;
ThreadFromQObject * myWork = new ThreadFromQObject();
connect(thread, SIGNAL(started()), myWork , SLOT(runThread()));
myWork ->moveToThread(thread);
thread->start();
注意:
- 声明的槽函数作为线程执行的入口,通过connect建立连接,放入线程执行
本文只涉及建立线程,未涉及线程安全和内存泄漏等问题(见后续章节)