Search code examples
qtqmlqt-quick

Attribute parent dynamically to a QML component based in a condition


How to attribute a parent dynamically when the QML component is being created based in a condition?

Example:

//FirstFile.qml

SecondFile{

  Rectangle {
    id: bodyRect

  }    
}

//SecondFile.qml

Rectangle{
  id: rectangleId

  Flickable{
    id: flickableId

  }    
}

In this example the parent of bodyRect is rectangleId.

How to attribute the flickableId as a parent of bodyRectif a condition is true ?


Solution

  • Well, it really depends on what you actually want to achieve, which is totally unclear from the question as it stands right now.

    If you use dynamic object instantiation, you can simply pass the desired parent to the function:

    someComponent.createObject(condition ? parent1 : parent2)
    

    Additionally, you can change the visual parent of an object based on a condition:

      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"
        }
      }
    

    The blue rectangle will be dynamically reparented to either the red or the green rectangle as cond changes.

    Keep in mind that you cannot really do stuff across different files, unless the objects happen to represent actual instances that have visibility in the object tree.