轉載請注明鏈接與作者huihui1988
QThread的用法其實比較簡單,只需要派生一個QThread的子類,實現其中的run虛函數就大功告成, 用的時候創建該類的實例,調用它的start方法即可。但是run函數使用時有一點需要注意,即在其中不能創建任何gui線程(諸如新建一個QWidget或者QDialog)。如果要想通過新建的線程實現一個gui的功能,那么就需要通過使用線程間的通信來實現。這里使用一個簡單的例子來理解一下 QThread中signal/slot的相關用法。
首先,派生一個QThread的子類
MyThread.h
- class MyThread: public QThread
- {
- Q_OBJECT
- public:
- MyThread();
- void run();
- signals:
- void send(QString s);
- };
void send(QString s)就是定義的信號
MyThread.cpp
- #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
- class MyWidget : public QWidget {
- Q_OBJECT
- public:
- MyWidget (QWidget *parent = 0);
- ~Widget();
- public slots:
- void receiveslot(QString s);
- };
void receiveslot(QString s)就用來接受發出的信號,並且實現參數的傳遞。
MyWidget .cpp
- #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
- #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即會彈出一個提醒窗口,線程間通信就此完成。
http://blog.csdn.net/huihui1988/article/details/5665432