Search code examples
qtqmlqqmlcomponent

Communication between 2 different objects in 2 different QML files


I have one main.qml file and I have other "example.qml" file. When I push a button from "example.qml" file I want to change a text in "main.qml" file. I tried defining the source of the text. I tried send signal. I tried using loader but always came to a dead end.

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Imagine 2.12
import QtQuick.Window 2.0

//main.qml
Window {
       visible: true
       width: 1080
       height: 720
       color: "black"
       title: qsTr("MY GUI")

    Text {
       id: deneme
       x: 100
       y: 400
       color: "white"
       text: "Trial"

   }
} 
//example.qml

Item {
    id: difflock

    Rectangle{
        id: diffLockRect
        width: 1080
        height: 720
        color: "red"
        signal  mySignal

        Button{.


          onClicked: main.deneme.text = "Finally"
        }
    }
}


Solution

    • Create a new qml named by Example.qml(first letter should be capital)
    • Define in main.qml
    • Example.qml can access the objects in main.qml

    main.qml

    import QtQuick 2.12
    import QtQuick.Layouts 1.12
    import QtQuick.Controls 2.12
    import QtQuick.Controls.Imagine 2.12
    import QtQuick.Window 2.0
        Window {
               visible: true
               width: 1080
               height: 720
               color: "black"
               title: qsTr("MY GUI")
    
               Example{id:rfrnc} // You can also reach the other qml objects by using this id
    
            Text {
               id: deneme
               x: 100
               y: 400
               color: "white"
               text: "Trial"
    
           }
        }
    

    Example.qml

    import QtQuick 2.12
    import QtQuick.Layouts 1.12
    import QtQuick.Controls 2.12
    import QtQuick.Controls.Imagine 2.12
    import QtQuick.Window 2.0
    
    Item {
        id: difflock
    
        Rectangle{
            id: diffLockRect
            width: 1080
            height: 720
            color: "red"
            signal  mySignal
    
            Button{
    
    onClicked: deneme.text = "Finally"
            }
        }
    }