Andrew Tomazos
Andrew Tomazos

Reputation: 68648

How can I refer to an item by id in another QML file?

So lets say I have the following two qml files:

main.qml:

    Window {
       /* ... */

       onSomething: mybutton.text = "foo"

       Foo {}
    }

Foo.qml:

Item {
    /* ... */

    Button {
      id: mybutton

      /* ... */
    }
}

When onSomething is called it will generate a runtime error:

ReferenceError: mybutton is not defined

Whats the correct way to refer to the mybutton button from mail.qml ? Or how else can I organize this?

(Are the ids file scoped?)

Upvotes: 2

Views: 773

Answers (1)

Farshid616
Farshid616

Reputation: 1484

You should make an alias from your object that want to be accessible like below

Foo.qml

Item {
property alias buttonText: mybutton.text
/* ... */

Button {
  id: mybutton

  /* ... */
}

}

then use it on your main.qml

main.qml

Window {
   /* ... */

   onSomething: myfoo.buttonText = "foo"

   Foo 
   {
      id: myfoo
   }
}

Also you can alias your Button object and use it. As you guess the ids are scoped and you should make them accessible.

Upvotes: 4

Related Questions