代码之家  ›  专栏  ›  技术社区  ›  sftpck

基于条件将父项动态地指定给QML组件

  •  0
  • sftpck  · 技术社区  · 8 年前

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

    例子:

    //第一个文件。qml公司

    SecondFile{
    
      Rectangle {
        id: bodyRect
    
      }    
    }
    

    //第二个文件。qml公司

    Rectangle{
      id: rectangleId
    
      Flickable{
        id: flickableId
    
      }    
    }
    

    在本例中 bodyRect rectangleId .

    如何将 flickableId 作为 bodyRect公司 如果条件为真?

    1 回复  |  直到 8 年前
        1
  •  1
  •   dtech    8 年前

    嗯,这真的取决于你真正想要实现什么,从目前的问题来看,这是完全不清楚的。

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

    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 变化。

    请记住,除非对象恰好表示在对象树中具有可见性的实际实例,否则您无法跨不同的文件执行操作。