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

QML scope: how to access objects?



  • Hi,

    I have 2 files

    //Cat.qml
    
    Item {
        Rectangle {
            id: testRect
            width: 50
            height: 50
            border.color: "black"
    
            function printTest(txt) {
                console.log(txt)
            }
        }
    
        Button {
            anchors.left: testRect.right
            width: 50
            height: 50
            onClicked: {
                testRect.printTest("button click")
            }
        }
    
    }
    
    //main.qml
    Window {
        visible: true
        width: 640
        height: 480
    
        Cat {
            id: testCat
        }
    
        Button {
            x: 100
            onClicked: {
    
            }
        }
    }
    

    How to access Rectangle in Cat.qml?
    More specifically I want to printTest in main.qml onClicked


  • Moderators

    @Eligijus
    you can expose it as a property for example:

    // Cat.qml
    
    Item {
        property alias embeddedRect: testRect
    
        Rectangle {
            id: testRect
            ....
        }
    
       ...
    }
    
    //main.qml
    
    Window {
        
        // use 'testCat.embeddedRect'
    
        Cat {
            id: testCat
        }
    
        ....
    }
    


  • @Eligijus On the other hand you don't need to place printTest inside testRect, you can place it (or any other function) directly inside the top level item because you have access to all ids and properties inside the same file. Especially in your simplified example the function could be as well global or located anywhere because it's completely self-contained and uses only the argument.

    Item {
        //can be called in your main.qml as testCat.printTest("works well"):
        function printTest(txt) {
                console.log(txt)
                console.log(testRect.width)
        }
        Rectangle {
            id: testRect
            width: 50
            height: 50
            border.color: "black"
        }
    }
    


  • @Eeli-K In that particular example yes that would work. But I forgot to mention that I provided simplified example. In my case Rectange(testRect) is C++ object and printTest is a public slot. So I can't simply move that slot to top level item.



  • @Eligijus OK. Raven-worx's solution may be the best for you, it's simple. Another option is a function which delegates the call:

    Item {
        //can be called in your main.qml as testCat.printTest("works well"):
        function printTest(txt) {
               testItem.printTest(txt)
        }
        MyItemWithASlot {
            id: testItem
        }
    }
    


  • @Eeli-K Yeah i'm sticking with the Raven-worx's solution it's elegant and simple. Thanks for all your input.


Log in to reply