Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - How to connect signal from loader item, if loader source changes dynamically

Tags:

qt

qml

I have an application which needs the screen to be switched between multiple available screens. I am checking if this is possible with loader in qml.

The issue i am facing is connecting signals from loaded item.

I use an application example in qt documentation and found CreateConnection in application qml cannot have if condition.

I also tried to make it signal slot connection in a function and call in on source change of loader, but that too did not work.

Application.qml

import QtQuick 2.0

Item {
    width: 100; height: 100

    Loader {
       id: myLoader
       source: "MyItem.qml"
    }

    Connections {
        target: myLoader.item
        // here i tried using if (myLoader.item == "qrc:MyItemOne.qml") , but can't use if
        onChangeToSecond: {
               myLoader.source = "MyItemTwo.qml"
        }

        onChangeToFirst: {
               myLoader.source = "MyItemOne.qml"
        }
    }
}

MyItemOne.qml

import QtQuick 2.0

Rectangle {
   id: myItem
   signal changeToSecond()

   width: 100; height: 100

   MouseArea {
       anchors.fill: parent
       onClicked: myItem.changeToSecond()
   }
}

MyItemTwo.qml

import QtQuick 2.0

Rectangle {
   id: myItem
   signal changeToFirst()

   width: 100; height: 100

   MouseArea {
       anchors.fill: parent
       onClicked: myItem.changeToFirst()
   }
}

Someone knows any way to use loader for this, or loader should not be used for this?

like image 330
User Avatar asked Oct 30 '22 03:10

User


1 Answers

Your code works fine if I use MyItemOne.qml as the initial value for the myLoader.source (Qt5.6.0). However, it will print out a warning:

QML Connections: Cannot assign to non-existent property "onChangeToFirst"

which happens because MyItemOne does not define the changeToFirst signal. The ignoreUnknownSignals property of Connections element can be used to suppress the warning, or both screens should define the same set of signals.

Loader can be used if it does not matter that the previous view is always fully unloaded when switching.

like image 118
arhzu Avatar answered Nov 15 '22 05:11

arhzu