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.