Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a signal from one qml to another

Tags:

qt

qml

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?

like image 829
P.Ross Avatar asked Nov 03 '16 17:11

P.Ross


1 Answers

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.

like image 145
Manuel Schmitzberger Avatar answered Sep 30 '22 13:09

Manuel Schmitzberger