根据条件将父项动态地归因于 QML 组件

Attribute parent dynamically to a QML component based in a condition

如何在基于条件创建 QML 组件时动态地属性父级?

示例:

//FirstFile.qml

SecondFile{

  Rectangle {
    id: bodyRect

  }    
}

//SecondFile.qml

Rectangle{
  id: rectangleId

  Flickable{
    id: flickableId

  }    
}

在此示例中,bodyRect 的父项是 rectangleId

如果条件为真,如何将 flickableId 归因于 bodyRect 的父级?

好吧,这实际上取决于您实际想要实现的目标,目前的问题完全不清楚。

如果使用动态对象实例化,只需将所需的父对象传递给函数即可:

someComponent.createObject(condition ? parent1 : parent2)

此外,您可以根据条件更改对象的可视父级:

  property bool cond: false

  property Rectangle rect: Rectangle {
    Rectangle {
      parent: cond ? redrect : bluerect
      anchors.centerIn: parent
      width: 50
      height: 50
      color: "blue"
    }
  }

  MouseArea {
    anchors.fill: parent
    onClicked: cond = !cond
  }

  Row {
    Rectangle {
      id: redrect
      width: 200
      height: 200
      color: "red"
    }
    Rectangle {
      id: bluerect
      width: 200
      height: 200
      color: "green"
    }
  }

随着 cond 更改,蓝色矩形将动态重新设置为红色或绿色矩形的父级。

请记住,您不能真正跨不同的文件执行操作,除非对象恰好代表在对象树中具有可见性的实际实例。