初學QT,前期由於信號與槽只能在QT界面上面方便的使用,沒有想到只要繼承QObject便能使用且支持多線程操做。web
爲了可以讓後臺自定義類可以使用信號與槽,首先在自定義類繼承QObjectapi
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.cppapp
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.cppoop
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); }
傳遞消息的方式有四個取值:ui
Qt::DirectConnection When emitted, the signal is immediately delivered to the slot. 假設當前有4個slot鏈接到QPushButton::clicked(bool),當按鈕被按下時,QT就把這4個slot按鏈接的時間順序調用一遍。顯然這種方式不能跨線程(傳遞消息)。this
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。這種方式既能夠在線程內傳遞消息,也能夠跨線程傳遞消息。spa
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