信号槽机制注意要点

1.Qt中的信号槽被连接N次,则信号发射1次,槽函数被调用N次。解决方法如下:

默认情况下每一个连接都会收到一个信号,所以如果你把同一个信号与槽连接了多次(N),那么当信号发送后,这个槽也会被调用N次。所以这里千万要注意,我以前就遇到这么一个Bug过,所以写连接的代码的时候要注意哦,特别是有的时候在可能会出现重复调用的函数里面对某些信号和槽做连接,这样的话这个函数被调用多次就会造成连接的重复。要防止重复可以有一个方法:在 connect() 函数中传递 Qt::UniqueConnection 参数而不是默认的Qt::AutoConnection,这样的话如果连接已经存在,那么这次连接会失败(返回false)。

关于信号槽连接类型如下所述:

enum Qt::ConnectionType
This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.

Constant Value                                                                              Description
Qt::AutoConnection         0 (default) If the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection. Otherwise, the slot is invoked directly, behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.
Qt::DirectConnection 1 The slot is invoked immediately, when the signal is emitted.
Qt::QueuedConnection 2 The 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::BlockingQueuedConnection 3 Same as QueuedConnection, except the current thread blocks until the slot returns. This connection type should only be used where the emitter and receiver are in different threads.
Note: Violating this rule can cause your application to deadlock.


Constant Value Description
Qt::UniqueConnection 0x80 This 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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值