Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to pass string value to loader iem?



  • I have a child.qml which will be loaded by a Loader.
    child.qml has a Text
    I want to pass a string to Text Dynamically.
    How to do it?
    Thanks for your guidance!



  • I define a property string origName in parent Loader,
    child.qml uses parent.origName to reference it.
    When I changed the source property of Loader, I got "TypeError: Cannot read property 'origName' of null"
    Is this a serious problem?



  • Hi, would you please show the code?



  • @Mr-Pang

    Below the methods typically used:

    yourLoader.setSource("child.qml", {"text": "yourMessages"}); // "text" is property name on child.qml item



  • @Devopia53
    Thank you very much.
    I am too careless to find out this method.



  • I think it would have help to have a complete working code as there many ways to use a loader and passing a string...

    Here is a sample with 4 ways :
    main.qml

    import QtQuick 2.2
    import QtQuick.Window 2.1
    import QtQuick.Controls 1.2
    import QtQml 2.2
    
    Window{
        id:page1
        visible:true;    width:640;    height:480
    
        Loader{
            id:yourLoader
            property string origName : "orig"
            source:"child.qml"
            anchors.top : button.bottom
        }
    
        Button{
            id:button
            text:"change"
    
            onClicked: {
                var curTime = new Date().toTimeString();
                yourLoader.setSource("child.qml", {"text": "text:"+curTime});
                yourLoader.item.text2 = "text2:"+curTime;
                yourLoader.origName = "text3 and text4:"+curTime;
            }
        }
    }
    

    and child.qml

    import QtQuick 2.0
    
    Item {
        id: root
        property string text : "init 1"
        property string text2 : "init 2"
        property string text3 : yourLoader.origName
        property string text4 : parent ? parent.origName : ""
    
        Text{
            text : parent.text + "\n" + parent.text2 + "\n" + parent.text3 + "\n" + parent.text4
        }
    }
    

    as you can see the 3 first ways are working fine without error whereas the 4th requires to check the validity of parent before accessing its property.


Log in to reply