Qt线程 - 继承QObject方式
Qt使用线程有两种方式,在新版本的Qt中,Qt官方推荐使用继承QObject的方式,本文档记录使用此方法线程的实验过程。
本文转自:http://beself.top/2018/11/09/qt-thread-inherit-qobject/
线程实验总结
在实验1 至实验5终于得出结论,使用继承QObject的方式实现多线程的方式,
- 使用继承QObject的方式实现多线程的方式经过实验证明是可以的,具体过程请仔细观察实验过程记录;
- 本次实验中实验了终止线程的一种方式,通过变量来跳出循环线程;
- 在使用变量共享的方式退出线程是使用QMutexLocker的方式进行变量保护;
官方示例
class Worker : public QObject
{
Q_OBJECT
public slots:
void doWork(const QString ¶meter) {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals:
void resultReady(const QString &result);
};
class Controller : public QObject
{
Q_OBJECT
QThread workerThread;
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &Controller::operate, worker, &Worker::doWork);
connect(worker, &Worker::resultReady, this, &Controller::handleResults);
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
public slots:
void handleResults(const QString &);
signals:
void operate(const QString &);
};
从示例中可以看出,总结一下步骤:
- 新建一个类并继承QObject基类;
- 在主线程中new出这个新建的类,新类不能有父类,再声明一个QThread类,并将类moveToThread到线程中;
- 通过start开始线程;
- 退出线程时需要退出线程;
更多实验过程
更多实验过程请查看原文:http://beself.top/2018/11/09/qt-thread-inherit-qobject/