关于Qt的QThread

第一种方式 继承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();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值