qtqmlqtquick2

Is it possible to connect multiple slots to one signal?


I am trying to figure out the best way for a QML object to send out a signal and for many other QML elements to respond to it. Normally, if you create signal mySignal then you have a handler automatically created for you called onMySignal but that handler exists only within the same element that created the signal.

A particularly inelegant solution could be to store an array of QML elements you want updated when a signal occurs, and then in your handler you loop through all those elements and do what you need.

I'd be surprised if there wasn't an easier way. Am I missing an obvious use case of the signal-slot mechanism in QML?


Solution

  • You can use a Connections component in QML to achieve this

    The Item with the signal we want to catch:

    MyItem {
      id: itemWithSignal
    
      onMySignal: {
        console.log("I am sending my signal");
      }
    }
    

    In another Item we use the Connections component:

    MyOtherItem {
      id: itemSomewhereElse
    
      Connections {
        target: itemWithSignal
    
        onMySignal: {
          console.log("itemWithSignal just emitted its signal!");
        }
      }
    }
    

    You can also use connect() in QML so it would be something like this:

    MyOtherItem {
      id: itemSomewhereElse
    
      onMyOtherSignal: {
        console.log("My signal is connected!");
      }
    
      Component.onCompleted: {
        itemWithSignal.mySignal.connect(itemSomewhereElse.myOtherSignal);
      }
    }