0
votes

I have two qml files, MyButton.qml and testmain.qml I use MyButton, as a delegate in a listview inside testmain.qml. MyButton has a 'text' property. I want to read this property from outside the Loader, like in the example below.

testmain.qml

import QtQuick 2.10
import QtQuick.Controls 2.4
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.3

ApplicationWindow {
    id: appWindow
    Material.theme: Material.Dark
    title: qsTr("Test QML")
    visible: true

    width: 640
    height: 480

    Rectangle {
        id: myRec
        anchors.fill: parent
        color: 'grey'

        ListView{
            anchors.fill: parent
            model: 10
            delegate: Loader{
                id:myLoader
                source: "MyButton.qml"
                onLoaded: {
                    console.log("Loader loaded")
                }
            }

            Component.onCompleted: {
            console.log("Referencing loader item: " + myLoader.item.text)
        }
        }
    }
}

MyButton.qml

import QtQuick 2.10
import QtQuick.Controls 2.4
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.3

Rectangle {
    id: button
    width: 145; height: 60
    color: "blue"
    smooth: true; radius: 9
    property alias text: label.text
    border {color: "#B9C5D0"; width: 1}

    gradient: Gradient {
        GradientStop {color: "#CFF7FF"; position: 0.0}
        GradientStop {color: "#99C0E5"; position: 0.57}
        GradientStop {color: "#719FCB"; position: 0.9}
    }

    Text {
        id: label
        anchors.centerIn: parent
        text: "Click Me!"
        font.pointSize: 12
        color: "blue"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: console.log(text + " clicked")
    }
}

Right now I'm getting the following error: file:///D:/Windows/Documents/qmltest/QML/testmain.qml:33: ReferenceError: myLoader is not defined I'm unsure as to what I'm doing wrong. Line 33 is where I'm trying to reference the loader's item console.log("Referencing loader item: " + myLoader.item.text)

1

1 Answers

0
votes

Component.onCompleted is emitted when the construction of the Loader is complete, and that does not imply that the component that loads the loader is this. You must do that reading on onLoaded signal:

delegate: Loader{
    id:myLoader
    source: "MyButton.qml"
    onLoaded: {
        console.log("Loader loaded")
        console.log(myLoader.item.text)
    }
}