第一種方式 繼承QThread方式:
class ThreadTest : public QThread {
......
signals: void test();
......
}
ThreadTest *thread = new ThreadTest(this);
//這2個 相同, 都在主線程中執行槽函數
connect(thread, SIGNAL(test()), thread, SLOT(doTest()));
connect(thread, SIGNAL(test()), thread, SLOT(doTest2()), Qt::QueuedConnection);
//使用DirectConnection ,信號在什麼線程中發出來,槽函數在什麼線程中執行
connect(thread, SIGNAL(test()), thread, SLOT(doTest3()), Qt::DirectConnection);
thread->start();
// 使用Qt::QueuedConnection時,接收者所在什麼線程,槽函數便在什麼線程中執行
// 使用Qt::DirectConnection時,信號在什麼線程發出,槽函數便在什麼線程中執行
第二種 使用moveToThread:
QThread *qthread = new QThread(this);
qthread->start();
DoWork *work1 = new DoWork; //不能指定父類
DoWork *work2 = new DoWork; //不能指定父類
DoWork *work3 = new DoWork; //不能指定父類
work1->moveToThread(qthread);
work2->moveToThread(qthread);
work3->moveToThread(qthread);
connect(qthread, &QThread::finished, work1, &QObject::deleteLater);
connect(qthread, &QThread::finished, work2, &QObject::deleteLater);
connect(qthread, &QThread::finished, work3, &QObject::deleteLater);
//這2個 相同, 槽函數test未在線程中執行
//work->test();
//QMetaObject::invokeMethod(work1, "test", Qt::DirectConnection);
//QMetaObject::invokeMethod(work2, "test", Qt::DirectConnection);
//QMetaObject::invokeMethod(work3, "test", Qt::DirectConnection);
//槽函數test在線程中執行
QMetaObject::invokeMethod(work1, "test", Qt::QueuedConnection);
QMetaObject::invokeMethod(work2, "test", Qt::QueuedConnection);
QMetaObject::invokeMethod(work3, "test", Qt::QueuedConnection);
//槽函數test在線程中調用
//connect(this, SIGNAL(test()), work1, SLOT(test()), Qt::QueuedConnection);
//connect(this, SIGNAL(test()), work2, SLOT(test()), Qt::QueuedConnection);
//connect(this, SIGNAL(test()), work3, SLOT(test()), Qt::QueuedConnection);
//emit this->test();