QML,如何从父级访问Loader项目字段?

时间:2019-01-10 18:55:17

标签: qt qml

我有两个qml文件,MyButton.qmltestmain.qml 我使用MyButton作为testmain.qml内列表视图中的委托。 MyButton具有“文本”属性。 我想从Loader外部读取此属性,如以下示例所示。

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")
    }
}

现在我遇到以下错误: file:///D:/Windows/Documents/qmltest/QML/testmain.qml:33: ReferenceError: myLoader is not defined我不确定自己在做什么错。第33行是我尝试引用加载程序的项目console.log("Referencing loader item: " + myLoader.item.text)

的地方

1 个答案:

答案 0 :(得分:0)

Component.onCompleted在加载程序的构造完成时发出,并不意味着加载加载程序的组件就是这个。您必须在onLoaded信号上进行读取:

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