QThread与其他线程间相互通信

时间:2023-03-10 00:07:31
QThread与其他线程间相互通信

转载请注明链接与作者huihui1988

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

首先,派生一个QThread的子类

MyThread.h

  1. class MyThread: public QThread
  2. {
  3. Q_OBJECT
  4. public:
  5. MyThread();
  6. void run();
  7. signals:
  8. void send(QString s);
  9. };

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

MyThread.cpp

  1. #include "MyThread.h"
  2. MyThread::MyThread()
  3. {
  4. }
  5. void MyThread::run()
  6. {
  7. while(true)
  8. {
  9. sleep(5);
  10. emit send("This is the son thread");
  11. //qDebug()<<"Thread is running!";
  12. }
  13. exec();
  14. }

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

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

MyWidget .h

  1. class MyWidget : public QWidget {
  2. Q_OBJECT
  3. public:
  4. MyWidget (QWidget *parent = 0);
  5. ~Widget();
  6. public slots:
  7. void receiveslot(QString s);
  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. void MyWidget::receiveslot(QString s)
  9. {
  10. QMessageBox::information(0,"Information",s);
  11. }

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

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

main.cpp

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

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

http://blog.csdn.net/huihui1988/article/details/5665432