Qt World Summit: Register Today!

ReferenceError: data1 is not defined

  • Hello,

    I would like to use external file with main.qml, but not clear for me how can I set text in other .qml file.

    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtQuick.Controls 2.13
    Window {
        visible: true
        width: 640
        height: 480
        color: "#574d4d"
        title: qsTr("Hello World")
        Rectangle {
            id: rectangle
            x: 13
            y: 13
            width: 614
            height: 454
            color: "#090808"
            border.color: "#fbe74e"
            border.width: 2
        Button {
            id: button
            x: 30
            y: 404
            text: qsTr("Button")
            onClicked: data1.text = Math.floor(Math.random() * 10)
        Datarec {

    and Datarec.qml

    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtQuick.Controls 2.13
    Rectangle {
        id: datarec
        width: 143
        height: 70
        color: "#413939"
        Text {
            id: element
            x: 8
            y: 20
            color: "#e7f310"
            text: qsTr("32,01 C")
            font.family: "Tahoma"
            font.bold: true
            font.pixelSize: 30
        Text {
            id: data1
            x: 9
            y: 12
            color: "#fbfbfb"
            text: qsTr("Valami Infó")
            font.pixelSize: 12

    If onClicked fires the following error comes_:ReferenceError: data1 is not defined.
    Could you give me instruction how can I use external .qml.

    Thanks, Joe

  • Hi @MJoco

    The reason is explained here: https://doc.qt.io/qt-5/qtqml-documents-scope.html

    You have to add this following line in the root Item of Datarect.qml (id: datarec)

    property alias data1: data1


    property Text mytext: mytext

    and give Datarec an id in main.qml

    Datarec { id: datarec }

    Then you can get text from data1 by datarect.data1.text

     onClicked: datarec.data1.text = Math.floor(Math.random() * 10)

    You have many other possibilities to do this, like directly alias the text, or to use a property declared in main.qml in Datarec.qml, and so on....


Log in to reply