第一种方式 继承QThread方式:
class ThreadTest : public QThread {
......
signals: void test();
property:
void run() override {
......
emit 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();