本文介紹的是QT中實現Thread與GUI主線程通,目前只會一種,採用信號槽機制。
通常情況下,信號和槽機制可以同步操作,這就意味着在發射信號的時候,使用直接函數即可以立刻調用連接到一個信號上的多個槽。然而,當連接位於不同線程中的對象時,這一機制就會變得不同步起來,可以通過修改QObject::connect()的第5個可選參數而改變。
connect的第五個參數Qt::QueuedConnection表示槽函數由接受信號的線程所執行,如果不加表示槽函數由發出信號的次線程執行。當傳遞信號的參數類型不是QT的元類型時要先註冊,關於QT的元類型可以參看QT文檔
QMetaType這個類裏面列舉了所有的元類型。
以QString爲例,註冊時首先Q_DECLARE_METATYPE(QString);然後,int id=qRegisterMetaType<QString>("QString");加上這兩句就註冊成功了。
貼個示例的代碼,次線程不斷更改一個QString傳給GUI主線程,主線程在GUI界面上顯示。
- mythread.h
- #ifndef MYTHREAD_H
- #define MYTHREAD_H
- #include <QThread>
- class MyThread : public QThread
- {
- Q_OBJECT
- public:
- MyThread();
- ~MyThread();
- protected:
- void run();
- signals:
- void changeText(QString str);
- };
- #endif // MYTHREAD_H
- widgett.h
- #ifndef WIDGETT_H
- #define WIDGETT_H
- #include <QtGui/QMainWindow>
- #include "ui_widgett.h"
- class WidgetT : public QMainWindow
- {
- Q_OBJECT
- public:
- WidgetT(QWidget *parent = 0, Qt::WFlags flags = 0);
- ~WidgetT();
- private:
- Ui::WidgetTClass ui;
- private slots:
- void labelSetText(QString qstr);
- };
- #endif // WIDGETT_H
- mythread.cpp
- #include "mythread.h"
- MyThread::MyThread()
- : QThread()
- {
- }
- MyThread::~MyThread()
- {
- }
- void MyThread::run(){
- static int i=0;
- while(true)
- {
- ++i;
- QString strnum = QString::number(i);
- emit changeText(strnum);
- QThread::sleep(1);
- }
- }
- widgett.cpp
- #include "widgett.h"
- #include "mythread.h"
- Q_DECLARE_METATYPE(QString);
- WidgetT::WidgetT(QWidget *parent, Qt::WFlags flags)
- : QMainWindow(parent, flags)
- {
- ui.setupUi(this);
- MyThread *mythread = new MyThread;
- int id=qRegisterMetaType<QString>("");
- connect(mythread,SIGNAL(changeText(QString)),this,SLOT(labelSetText(QString)),Qt::QueuedConnection);
- mythread->start();
- }
- WidgetT::~WidgetT()
- {
- }
- void WidgetT::labelSetText(QString qstr){
- ui.label->setText(qstr);
- }
小結:QT中實現Thread與GUI主線程連通方法的內容介紹完了,在罈子裏逛了一圈,解決線程的問題還真不少,最後還是希望本文對你有幫助。