QThread与其他线程间相互通信

来源:互联网 发布:访客网络速度设置 编辑:程序博客网 时间:2024/06/05 01:07

作者:leohui1988

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

首先,派生一个QThread的子类 

MyThread.h

view plaincopy to clipboardprint?
class MyThread: public QThread  
{  
    Q_OBJECT  
public:  
    MyThread();  
    void run();  
signals:  
    void send(QString s);  
};  
 
void send(QString s)就是定义的信号

MyThread.cpp

view plaincopy to clipboardprint?
#include "MyThread.h"  
MyThread::MyThread()  
{  
}  
void MyThread::run()  
{  
    while(true)  
    {  
    sleep(5);  
    emit send("This is the son thread");  
    //qDebug()<<"Thread is running!";  
    }  
    exec();  
}  
 
emit send("This is the son thread") 为发射此信号,在run中循环发送,每次休眠五秒

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

MyWidget .h

view plaincopy to clipboardprint?
class MyWidget : public QWidget {  
    Q_OBJECT  
public:  
    MyWidget (QWidget *parent = 0);  
    ~Widget();  
public slots:  
    void receiveslot(QString s);  
};  
 
void receiveslot(QString s)就用来接受发出的信号,并且实现参数的传递。

MyWidget .cpp

view plaincopy to clipboardprint?
#include "MyWidget.h"  
MyWidget::MyWidget(QWidget *parent) :QWidget(parent)  
{  
   
}  
MyWidget::~MyWidget()  
{  
}  
void MyWidget::receiveslot(QString s)  
{  
QMessageBox::information(0,"Information",s);  
}  
 
接受函数实现弹出发送信号中所含参数(QString类型)的消息框

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

main.cpp

view plaincopy to clipboardprint?
#include <QtGui>  
#include "MyWidget.h"  
int main(int argc, char *argv[])  
{  
    QApplication a(argc, argv);  
    MyWidgetw;  
    w.show();  
    MyThread *mth= new MyThread ;  
    QObject::connect(mth,SIGNAL(send(QString)),&w,SLOT(receiveslot(QString)));  
    mth->start();  
    return a.exec();  
}  
 
运行后,当MyWidget弹出后,子线程MyThread每隔5S即会弹出一个提醒窗口,线程间通信就此完成。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kelvinyeah/archive/2010/06/30/5705481.aspx