qt,使用moveToThread函数实现多线程

来源:互联网 发布:c语言编程50 编辑:程序博客网 时间:2024/05/22 12:00

在qt中想实现多线程一般有两种方法:1.继承QThread,重写run()函数;2.使用moveToThread()函数。moveToThread函数能将QObject派生类的对象移动到另一线程。调用此函数后,用信号触发该对象的槽函数,该槽函数就将运行于目标线程。

使用要点:

示例类:

class Woker : public  QObject

{

public slots:

  void slotDoSomething();

};


示例代码

Worker* worker = new Worker();

QThread* new_thread = new QThread(); //创建QThread对象

worker->moveToThread(new_thread); //将工作对象移动到新线程

connect(this,SIGNAL(startWork), worker ,SLOT(slotDoSomething()), Qt::QueuedConnection); //连接信号和槽

new_thread->start(); //启动线程

//需要运行slotDoSomething时发送信号

emit startWork();


注意事项:

1.派生于QWidget的类没有这个功能。

2.只有用信号来触发函数,函数才会运行于子线程,直接调用的话,函数还是会运行于调用函数的线程。

3.不要忘了启动线程,调用start()函数。

4.连接信号槽时使用Qt::QueuedConnection参数。


0 0