`
dowhathowtodo
  • 浏览: 780563 次
文章分类
社区版块
存档分类
最新评论

QThread与其他线程间相互通信

 
阅读更多

转载请注明链接与作者huihui1988

QThread的用法其实比较简单,只需要派生一个QThread的子类,实现其中的run虚函数就大功告成, 用的时候创建该类的实例,调用它的start方法即可。但是run函数使用时有一点需要注意,即在其中不能创建任何gui线程(诸如新建一个QWidget或者QDialog)。如果要想通过新建的线程实现一个gui的功能,那么就需要通过使用线程间的通信来实现。这里使用一个简单的例子来理解一下 QThread中signal/slot的相关用法。

首先,派生一个QThread的子类

MyThread.h

  1. classMyThread:publicQThread
  2. {
  3. Q_OBJECT
  4. public:
  5. MyThread();
  6. voidrun();
  7. signals:
  8. voidsend(QStrings);
  9. };

void send(QString s)就是定义的信号

MyThread.cpp

  1. #include"MyThread.h"
  2. MyThread::MyThread()
  3. {
  4. }
  5. voidMyThread::run()
  6. {
  7. while(true)
  8. {
  9. sleep(5);
  10. emitsend("Thisisthesonthread");
  11. //qDebug()<<"Threadisrunning!";
  12. }
  13. exec();
  14. }

emit send("This is the son thread") 为发射此信号,在run中循环发送,每次休眠五秒

之后我们需要在另外的线程中定义一个slot来接受MyThread发出的信号。如新建一个MyWidget

MyWidget .h

  1. classMyWidget:publicQWidget{
  2. Q_OBJECT
  3. public:
  4. MyWidget(QWidget*parent=0);
  5. ~Widget();
  6. publicslots:
  7. voidreceiveslot(QStrings);
  8. };

void receiveslot(QString s)就用来接受发出的信号,并且实现参数的传递。

MyWidget .cpp

  1. #include"MyWidget.h"
  2. MyWidget::MyWidget(QWidget*parent):QWidget(parent)
  3. {
  4. }
  5. MyWidget::~MyWidget()
  6. {
  7. }
  8. voidMyWidget::receiveslot(QStrings)
  9. {
  10. QMessageBox::information(0,"Information",s);
  11. }

接受函数实现弹出发送信号中所含参数(QString类型)的消息框

在main()函数中创建新线程,来实现两个线程间的交互。

main.cpp

  1. #include<QtGui>
  2. #include"MyWidget.h"
  3. intmain(intargc,char*argv[])
  4. {
  5. QApplicationa(argc,argv);
  6. MyWidgetw;
  7. w.show();
  8. MyThread*mth=newMyThread;
  9. QObject::connect(mth,SIGNAL(send(QString)),&w,SLOT(receiveslot(QString)));
  10. mth->start();
  11. returna.exec();
  12. }

运行后,当MyWidget弹出后,子线程MyThread每隔5S即会弹出一个提醒窗口,线程间通信就此完成。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics