再次了解信号与槽

0.connect函数原型

//一般使用,不会关注第5个参数
connect(ui.btn, SIGNAL(clicked()), this, SLOT(slot_openBtn()));

//函数原型,第5个参数默认为 Qt::AutoConnection
connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType = Qt::AutoConnection);

一般情况下我们用connect函数不会关注它的最后一个参数,因为它默认是Qt::AutoConnection会自适应,但是有时候还是需要自己指定一下,比较靠谱。

那么我们来关注一下这个枚举类型 Qt::ConnectionType

ConstantValueDescription解释
Qt::AutoConnection0 If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.自动连接:(默认值)如果信号在接收者所依附的线程内发射,则等同于直接连接。如果发射信号的线程和接受者所依附的线程不同,则等同于队列连接
Qt::DirectConnection1The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread.直接连接:当信号发射时,槽函数将直接被调用。无论槽函数所属对象在哪个线程,槽函数都在发射信号的线程内执行。[这种方式不能跨线程传递消息]
Qt::QueuedConnection2The slot is invoked when control returns to the event loop of the receiver’s thread. The slot is executed in the receiver’s thread.队列连接:当控制权回到接受者所依附线程的事件循环时,槽函数被调用。槽函数在接收者所依附线程执行。[这种方式既可以在线程内传递消息,也可以跨线程传递消息]
Qt::BlockingQueuedConnection3Same as Qt::QueuedConnection, except that the signalling thread blocks until the slot returns. This connection must not be used if the receiver lives in the signalling thread, or else the application will deadlock.Qt::QueuedConnection类似,但是发送消息后会阻塞,直到等到关联的slot都被执行。[说明它是专门用来多线程间传递消息的,而且是阻塞的]
Qt::UniqueConnection0x80his is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6.这个标志可以和上述标志通过或OR来结合使用。用于失能已经存在的connection

如果是在同一线程里面的操作(signal和slot都在同一个线程),那么用Qt::DirectConnection的效率最高(使用默认值Qt::AutoConnection也OK),主要是Qt::DirectConnection和Qt::QueuedConnection都需要储存到队列。
如果是多个线程之间进行消息传递(signal和slot都在不同线程),那么就要用到Qt::QueuedConnection或者Qt::BlockingQueuedConnection,不过一个是无阻塞的(Qt::QueuedConnection),一个是阻塞的(Qt::BlockingQueuedConnection,发送消息后会阻塞,直到所有的slot都被执行)。
 

1.自定义信号signals和emit信号

自定义信号用关键词signals:,类似C++的关键词public、private等用法一致。
       如果要自定义保护信号,就在protected:后声明。
       自定义信号只需要在头文件的类声明中声明, 然后将槽连接到信号即可,无需实现信号函数。
       信号函数与槽函数的返回值类型在任何时候都可以不同,而且如果不关心信号传递下来的参数,信号函数与槽函数的参数列表也可以不相同, 但是如果要访问信号传递下来的任何参数时, 信号函数 与 槽函数 的参数列表必须相同。

发送信号
       只需要用关键字emit后面加上要发的信号,如果要信号函数是有参数的,可以通过形参槽函数传值。

emit openMatlabEngine(m_isOpenMatlabEngine); 
emit openMatlabEngine(true);
emit openMatlabEngine(false); 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值