初学QT,前期因为信号与槽只能在QT界面上面方便的使用,没有想到只要继承QObject便能使用且支持多线程操作。 为了能够让后台自定义类能够使用信号与槽,首先在自定义类继承QObject 1.DayouTraderSpi.h #include "qobject.h" class DayouTraderSpi : public QObject,public CThostFtdcTraderSpi { 2.DayouTraderSpi.cpp DayouTraderSpi::~DayouTraderSpi() { //析构函数必须申明 } //自定义函数中触发信号 然后在界面定义槽函数及链接信号与槽 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是链接方式的一种。
传递消息的方式有四个取值: 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
在线程间使用信号槽进行通信时,需要注意必须使用元数据类型 Qt内生的元数据类型,如int double QString 等 如果要用自己定义的数据类型,需要在connect前将其注册为元数据类型。形式见代码。
|
|
来自: 昵称19447302 > 《QT开发》