Qt實現多線程下的信號與槽通訊


初學QT,前期因為信號與槽只能在QT界面上面方便的使用,沒有想到只要繼承QObject便能使用且支持多線程操作。

為了能夠讓后台自定義類能夠使用信號與槽,首先在自定義類繼承QObject

1.DayouTraderSpi.h

#include "qobject.h"
class DayouTraderSpi : public QObject,public CThostFtdcTraderSpi
{

//宏必須申明
Q_OBJECT
public: DayouTraderSpi(CThostFtdcTraderApi* api) :pUserApi(api){}; ~DayouTraderSpi(); signals:
//自定義的信號
void signal_add_int(QString); };

2.DayouTraderSpi.cpp

DayouTraderSpi::~DayouTraderSpi()
{
    //析構函數必須申明
}

//自定義函數中觸發信號
void DayouTraderSpi::ReqQryTradingAccount()
{

emit signal_add_int("ok");
}

然后在界面定義槽函數及鏈接信號與槽
1.DayouOption.h

class DayouOption : public QMainWindow
{
    Q_OBJECT
public:
    DayouOption(QWidget *parent = 0);
    ~DayouOption();
private slots:

    void set_lineEdit_text(QString);//自定義槽函數
};

2.DayouOption.cpp

DayouOption::DayouOption(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::DayouOptionClass)
{
    ui->setupUi(this);
                    MdApi = CThostFtdcMdApi::CreateFtdcMdApi();
    dayouMDSpi = new DayouMDSpi(MdApi);//創建回調處理類對象
    TraderApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
    dayouTraderSpi = new DayouTraderSpi(TraderApi);
//鏈接信號與槽 dayouTraderSpi指針必須是QObject類型,所以dayouTraderSpi必須繼承QObject。Qt::QueuedConnection是鏈接方式的一種。
connect(dayouTraderSpi, SIGNAL(signal_add_int(QString)), this, SLOT(set_lineEdit_text(QString)), Qt::QueuedConnection); } DayouOption::~DayouOption() { delete ui; } //槽函數實現
void DayouOption::set_lineEdit_text(QString str) { QMessageBox::warning(this, "查詢成功", str); }

 

傳遞消息的方式有四個取值:

Qt::DirectConnection When emitted, the signal is immediately delivered to the slot. 假設當前有4個slot連接到QPushButton::clicked(bool),當按鈕被按下時,QT就把這4個slot按連接的時間順序調用一遍。顯然這種方式不能跨線程(傳遞消息)。

Qt::QueuedConnection When emitted, the signal is queued until the event loop is able to deliver it to the slot. 假設當前有4個slot連接到QPushButton::clicked(bool),當按鈕被按下時,QT就把這個signal包裝成一個 QEvent,放到消息隊列里。QApplication::exec()或者線程的QThread::exec()會從消息隊列里取消息,然后調用 signal關聯的幾個slot。這種方式既可以在線程內傳遞消息,也可以跨線程傳遞消息。

Qt::BlockingQueuedConnection Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application. 與Qt::QueuedConnection類似,但是會阻塞等到關聯的slot都被執行。這里出現了阻塞這個詞,說明它是專門用來多線程間傳遞消息的。

Qt::AutoConnection If the signal is emitted from the thread in which the receiving object lives, the slot is invoked directly, as with Qt::DirectConnection; otherwise the signal is queued, as with Qt::QueuedConnection. 這種連接類型根據signal和slot是否在同一個線程里自動選擇Qt::DirectConnection或Qt::QueuedConnection

 


免責聲明!

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



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