Connections对象用来创建与QML信号的连接。

当和QML中的信号创建连接时,一个通常的做法是创建一个”on“的handler,当接收到信号是,这个handler会被唤醒。示例代码如下所示

  1. MouseArea {
  2. onClicked: {foo(parameters)}
  3. }

但是这种方法在一些情况上是无法工作的,例如

  • 同一个信号需要被多次连接
  • 在信号发送方的作用域之外的连接
  • 想要创建的连接不是在QML中进行的定义

在这种情况下,Connections这种类型便有了用武之地

比方说上述的代码,当采用Connections的方式时,可以写成如下方式

  1. MouseArea {
  2. Connections {
  3. function onClicked(mouse) { foo(mouse) }
  4. }
  5. }

不过,同时使用中,Connections的对象是其它对象的子对象,而非是信号发出方的子信号,所以通常采用下面的写法

  1. MouseArea {
  2. id: area
  3. }
  4. // ...
  5. Connections {
  6. target: area
  7. function onClicked(mouse) { foo(mouse) }
  8. }
Property Type Explaination
enabled bool This property holds whether the item accepts change events. By default, this property is true.
ignoreUnknownSignals bool Normally, a connection to a non-existent signal produces runtime errors.
If this property is set to true, such errors are ignored. This is useful if you intend to connect to different types of objects, handling a different set of signals for each object.
target Object This property holds the object that sends the signal.
If this property is not set, the target defaults to the parent of the Connection.
If set to null, no connection is made and any signal handlers are ignored until the target is not null.

参考资料

https://doc.qt.io/qt-5/qml-qtqml-connections.html