Qt线程 - 继承QObject方式

Qt线程 - 继承QObject方式

Qt使用线程有两种方式,在新版本的Qt中,Qt官方推荐使用继承QObject的方式,本文档记录使用此方法线程的实验过程。

本文转自:http://beself.top/2018/11/09/qt-thread-inherit-qobject/

线程实验总结

在实验1 至实验5终于得出结论,使用继承QObject的方式实现多线程的方式,

  1. 使用继承QObject的方式实现多线程的方式经过实验证明是可以的,具体过程请仔细观察实验过程记录;
  2. 本次实验中实验了终止线程的一种方式,通过变量来跳出循环线程;
  3. 在使用变量共享的方式退出线程是使用QMutexLocker的方式进行变量保护;

官方示例

class Worker : public QObject
{
    Q_OBJECT

public slots:
    void doWork(const QString &parameter) {
        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 &);
};

从示例中可以看出,总结一下步骤:

  1. 新建一个类并继承QObject基类;
  2. 在主线程中new出这个新建的类,新类不能有父类,再声明一个QThread类,并将类moveToThread到线程中;
  3. 通过start开始线程;
  4. 退出线程时需要退出线程;

更多实验过程

更多实验过程请查看原文:http://beself.top/2018/11/09/qt-thread-inherit-qobject/

猜你喜欢

转载自blog.csdn.net/ALONE_WORK/article/details/83902017
今日推荐