QThread與其他線程間相互通信


轉載請注明鏈接與作者huihui1988

 

QThread的用法其實比較簡單,只需要派生一個QThread的子類,實現其中的run虛函數就大功告成, 用的時候創建該類的實例,調用它的start方法即可。但是run函數使用時有一點需要注意,即在其中不能創建任何gui線程(諸如新建一個QWidget或者QDialog)。如果要想通過新建的線程實現一個gui的功能,那么就需要通過使用線程間的通信來實現。這里使用一個簡單的例子來理解一下 QThread中signal/slot的相關用法。

 

首先,派生一個QThread的子類  

MyThread.h

 

[cpp]  view plain copy
 
  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

 

[cpp]  view plain copy
 
  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

 

[cpp]  view plain copy
 
  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

 

[cpp]  view plain copy
 
  1. #include "MyWidget.h"  
  2. MyWidget::MyWidget(QWidget *parent) :QWidget(parent)  
  3. {  
  4.    
  5. }  
  6. MyWidget::~MyWidget()  
  7. {  
  8. }  
  9. void MyWidget::receiveslot(QString s)  
  10. {  
  11. QMessageBox::information(0,"Information",s);  
  12. }  

 

 

接受函數實現彈出發送信號中所含參數(QString類型)的消息框

 

在main()函數中創建新線程,來實現兩個線程間的交互。

 

main.cpp

 

[cpp]  view plain copy
 
  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM