Qt::UniqueConnection 是如何运作的?

How Qt::UniqueConnection works?

我不太明白 Qt::UniqueConnection 'flag' 是如何工作的。

Qt::UniqueConnection 是一个常量,来自 enum Qt::ConnectionType 那 "describes the types of connection that can be used between signals and slots".

如文档中所述,Qt::UniqueConnection 常量是:

Same as AutoConnection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection will fail. This connection type was introduced in Qt 4.6.

基于以下示例:

  for (int index = 0; index < 2; ++index)
  {
      QPushButton *myButton = new QPushButton("Button", this);
      connect(myButton, SIGNAL(clicked()), this, SLOT(doSomething()), Qt::UniqueConnection);
  }
  1. 它会根据按钮内存地址(我想)创建 2 个唯一连接(每个按钮一个)吗?

  2. 或者它会根据对象类型 (QPushButton) 和使用的信号和插槽只创建一个连接(第二个连接会失败)?

如果你不放这个标志,这意味着你可以做同样的连接:即。相同的发送者对象、相同的接收者对象、相同的信号和相同的 Slot 不止一次。

该插槽将被调用的次数与您建立此连接的次数一样多。

但是你不应该在不必要的时候滥用这个标志,因为它会验证你的连接是否已经存在,这意味着代码会变慢。

NoteQt::UniqueConnection 不适用于 lambda、非成员函数和仿函数;它们仅适用于连接到成员函数。