benrules2
benrules2

Reputation: 417

QML: Communicating with great grandparents through signals

I'm currently in the process of learning Qt for some cross platform development, and I'm trying to do everything using QML. I know there are lots of ways to solve my problem using C++, but I want to stay true to the model and use QML.

Here it is: If I am using a loader to display qml files as seen in the following code, how do I communicate with main.qml from secondPage.qml?

I assumed this would be through signals, but upon further reading it seems all actions on a signal are within the class that sent it ( using the connected method). Here is my resource on this: http://qt-project.org/doc/qt-4.8/qmlevents.html#connecting-signals-to-methods-and-signals

Alternatively, this may be the wrong design for a QML application. I'm trying to break away from using a single source file before things get too out of hand...

main.qml:

Rectangle {
    id: background
    ...
    Item{
        id: item1
        Loader {
          ....
            id:pageLoader;
            source : "secondPage.qml"
            focus:true;
         }
}

Upvotes: 2

Views: 1555

Answers (2)

Kunal
Kunal

Reputation: 3535

You can declare some signal in SecondPage.qml and connect those to Main.qml's function.

Like below, suppose you have secondPageSignal() defined in secondPage.qml and you want to call doSomething() function in Main.qml on secondPage's signal, you can connect that in onLoaded handler of Loader.

Rectangle {
    id: background
    ...

    function doSomething() {
    }
    Item{
        id: item1
        Loader {
          ....
            id: pageLoader;
            source : "secondPage.qml"
            focus:true;

            onLoaded:{
                 pageLoader.item.secondPageSignal.connect(background.doSomething);
            }
         }
    }
}

Upvotes: 3

koopajah
koopajah

Reputation: 25642

In secondPage.qml you have access to your background element directly because children have access to any of its parents in the hierarchy.

Another possibility is to declare a signal in your secondPage component, and then to connect the signal from this component to a signal in your great-grandparent in the onLoaded handler of your Loader. It makes it easier and cleaner if you want your component to be re-usable multiple times in your app without assu,ing what is parent is.

Upvotes: 2

Related Questions