user3365834
user3365834

Reputation:

qml use element id in another file

I have 3 files:

mainWindow.qml

       Rectangle{
            id: container

        Services{
            id: loger
        }
        ...//there is element code
 }

CategoryDelegate.qml

Item {
    id: delegate
...//there is element code
}

and MovieDialog.qml

Rectangle {
        id: movieDialog
...//there is element code
}

I need to use Services function in moviedialog and categorydelegate. From category delegate i can use it

Item {
    id: delegate

property string type: container.loger.getMovie(1)
//this code works well
}

But from moviedialog i cannot accept it!

Rectangle {
        id: movieDialog

property string type: container.loger.getMovie(1)
//this will not work
}

And i get error: "TypeError: Cannot call method 'getMovie' of undefined".

How can i fix it? Thanks in advance!

Upvotes: 2

Views: 6078

Answers (1)

Xander
Xander

Reputation: 687

In general that depends on the relation of your QML files. You can access the ID of parent files directly, but not child files.

example:

// Parent.qml
Item {
  id: parent1

  // has NO access to child1 id, you have to define your own id in this file (child2)
  // you can also use the same id again (child1) if you want

  Child {
    id: child2
    // has access to the parent1 id
  }
}

// Child.qml
Item {
  id: child1
  // has access to the parent1 id if only included into Parent.qml
}

I also noticed in your example you've changed IDs, that is not possible, an ID is always unique in the current context, so instead of container.loger.getMovie(1) your should only use loger.getMovie(1). If you need access to a child from outside of the file you need to define an property alias, e.g:

property alias log : loger

in your Rectangle (parent Item in the file, so you can access it from outside). This will actually create a public property of type Services in your case, so you can access it like any other property from outside of the file or wherever you need to.

I hope that helps with your problem.

Upvotes: 2

Related Questions