qml在另一个文件中使用元素id

qml在另一个文件中使用元素id,qml,Qml,我有3个文件: mainWindow.qml Rectangle{ id: container Services{ id: loger } ...//there is element code } CategoryDelegate.qml Item { id: delegate ...//there is element code } 和MovieDialog.qml R

我有3个文件:

mainWindow.qml

       Rectangle{
            id: container

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

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

Rectangle {
        id: movieDialog
...//there is element code
}
我需要使用moviedialog和categorydelegate中的服务功能。从类别代理中,我可以使用它

Item {
    id: delegate

property string type: container.loger.getMovie(1)
//this code works well
}
但从电影对话我不能接受

Rectangle {
        id: movieDialog

property string type: container.loger.getMovie(1)
//this will not work
}
我得到一个错误:“TypeError:无法调用未定义的方法'getMovie'

我怎样才能修好它?
提前谢谢

通常,这取决于QML文件的关系。 您可以直接访问父文件的ID,但不能访问子文件

例如:

// 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
}
我还注意到,在您的示例中,您更改了ID,这是不可能的,ID在当前上下文中始终是唯一的,因此您应该只使用
loger.getMovie(1)
而不是
container.loger.getMovie(1)
。如果需要从文件外部访问子级,则需要定义属性别名,例如:

property alias log : loger
在矩形中(文件中的父项,因此您可以从外部访问它)。在您的情况下,这实际上会创建一个类型为
Services
的公共属性,因此您可以像从文件外部或任何需要的地方访问任何其他属性一样访问它

我希望这有助于解决你的问题