实例化QThread
这个类会开辟一个新线程,默认运行run()
,还可以使用QObject::moveToThread
方法将任务对象移动至新线程,此时该任务对象的槽函数将运行在新线程中,可以自由的建立相关信号连接,默认是以Qt::QueuedConnection
方式,是线程安全的。
这样,我们可以有几种方式来创建线程完成工作:
任务对象继承QThread
,重写run()
方法;实例化对象后会自动运行run()
函数工作
任务对象继承QObject
,将工作任务实现在这个类的槽中;
创建QThead
,自定义类调用QObject::moveToThread
方法移动至新开辟的线程;
绑定该任务对象的槽,任意信号触发时,将在新线程中执行槽函数;
example 方法1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class WorkerThread : public QThread{ Q_OBJECT void run () override { QString result; emit resultReady (result) ; } signals: void resultReady (const QString &s) ; }; void MyObject::startWorkInAThread () { WorkerThread *workerThread = new WorkerThread (this ); connect (workerThread, &WorkerThread::resultReady, this , &MyObject::handleResults); connect (workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater); workerThread->start (); }
方法2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class Worker : public QObject{ Q_OBJECT public slots: void doWork (const QString ¶meter) { QString result; 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 &) ; };