How to send a signal from one qml to another

You don't communicate between qml files, the QML file is just a prototype, you communicate between the object instances.

  // Rect1.qml
  Rectangle {
    id: rect1
    signal mySignal
    Button {
      onClicked: rect1.mySignal()
    }
  }

  // Rect2.qml
  Rectangle { // Rect1.qml
    property alias text: txt.text
    Text {
      id: txt
    }
  }

And then you create the objects:

Rect1 {
  onMySignal: r2.text = "Goodbye world!"
}

Rect2 {
  id: r2
}

There are other ways to make a connection, however, connections happen between object instances, not qml files. The objects don't have to be in the same qml file too, but initially for simple things they will rarely be in different files.


For me this works with Connections and signal in one qml file as follow:

import QtQuick 2.4
import QtQuick.Controls 1.2

Item {
    id: item
    width: 200
    height: 200
    signal sendMessage(string msg, int compId)

    Button {
        text: "SendMessage"
        onClicked: sendMessage("hello",1)
    }

    Item {
        id: item1
        Connections {
            target: item
            onSendMessage: if(compId==1) { console.log("Hello by Comp 1") }
        }
    }

    Item {
        id: item2
        Connections {
            target: item
            onSendMessage: if(compId==2) { console.log("Hello by Comp 2") }
        }
    }
}

Of course the items with the Connections can be also in different files.

Tags:

Qt

Qml