8
votes

I cannot find a way to communicate from one qml file to the other one. I know there are many ways to send signals from qml to C++ slots and reverse, but all my research about signals between two different qml files failed. So I would be glad if someone can tell me, how I have to solve this problem.

First of all a little abstracted example to understand the problem in a better way...

The first QML in basics looks like that:

//MyQML1.qml
Rectangle
{    
     id: idMyRec1
     signal mySignalFromQML1()

  Button
  {
       id: idMyButton1
       onClicked:
       {
            idMyRec1.mySignalFromQML1();      //to send the signal
       }
   }
}

The 2nd one looks like this:

//MyQML2.qml
Rectangle
{
    id: idMyRec2

    Text{
         id: idMyText2
         text: "Hello World!"

         onMySignalFromQML1:       //to receive the signal from the other qml
         {                  
             idMyText2.text = "Good Bye World!";
         }
      }
}

So this button should change the text in my 2nd QML to "Good Bye World!" when clicked...but this doesn't work...are there any other ways to send signals from QML to another QML?! Or am I doing something wrong?

2

2 Answers

16
votes

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.

7
votes

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.