初学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