7

How to read property timeout located inside Loader object in Qt5 QML Quick 2.0?

import QtQuick 2.0

Rectangle {
    width: 100
    height: 100
    color: "black"

    property Component comp1 : Component {
        Rectangle {
            id: abc
            property int timeout: 5000
            width: 10; height: 10;
            color: "red"
        }
    }

    Loader {
        id: loader
        sourceComponent: comp1
    }

    Component.onCompleted: console.log( "timeout: " + loader.item.abc.timeout )
}

TypeError: Cannot read property 'timeout' of undefined

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Dmitry
  • 906
  • 1
  • 13
  • 32

1 Answers1

4

You have a few issues in your code, namely:

1) You do not assign an id identifier to your component object.

2) You are trying to inherit Component with a property which is needless in this simple code.

3) You do not use the item property properly for the Loader element.

4) You are referring to a property name rather the id of the Component. This is again back to the needless inheritance.

Based on the official documentation, you should be doing something like this:

import QtQuick 2.0

Rectangle {
    width: 100
    height: 100
    color: "black"

    Component {
        id: comp1
        Rectangle {
            id: abc
            property int timeout: 5000
            width: 10; height: 10;
            color: "red"
        }
    }

    Loader {
        id: loader
        sourceComponent: comp1
    }

    Component.onCompleted: console.log( "timeout: " + loader.item.timeout )
}
László Papp
  • 51,870
  • 39
  • 111
  • 135
  • It is good practice to use the "loaded" signal in the Loader to ensure the item has been loaded, for example, if "Loader.asynchronous" were set "true". In the Loader declaration: "onLoaded: console.log("timeout:", item.timeout)". – pixelgrease Jul 12 '21 at 19:12