在 QML 中,如何创建一个父组件来获取子组件实例并将它们放入父组件层次结构中?

Ros*_*ers 3 qt qml

Qt 的 QML 有许多小部件,您可以在其中实例化小部件,然后为其提供一个组件实例以供其显示和使用。

例如,Popup小部件可以这样使用:

Popup { // <-- Parent Component
  Rectangle { // <-- Child Component
    width: 100;
    height: 100;
    color: 'red';
  }
}
Run Code Online (Sandbox Code Playgroud)

我自己怎样才能做到这一点?如何编写一个自定义 QML 组件来获取子组件实例并将其放在我的树下?

如果我有一个愚蠢的组件,例如:

// File Parent.qml
Rectangle {
  default property var child_inst;
  width: child_inst.width + 20;
  width: child_inst.width + 20;
  color:'red';
  child_inst;  // <-- how is this done?
}
Run Code Online (Sandbox Code Playgroud)

并使用如下:

Parent {
  Text { text: 'hello world!' }
}
Run Code Online (Sandbox Code Playgroud)

我可以通过什么语法或机制将 实例化或移动child_inst为 my 的子级Parent

dte*_*ech 9

哇,这真是令人困惑的说法,但如果我理解正确的话,你想让孩子们自动重定向到其他对象。这是可能的,例如:

// Obj.qml
Rectangle {
  width: 50
  height: 50
  default property alias content: row.children
  Row {
    id: row
  }
}
Run Code Online (Sandbox Code Playgroud)

进而:

  Obj {    
    Rectangle {
      width: 10
      height: 10
      color: "red"
    }
    Rectangle {
      width: 10
      height: 10
      color: "green"
    }
    Rectangle {
      width: 10
      height: 10
      color: "blue"
    }    
  }
Run Code Online (Sandbox Code Playgroud)

结果是 rgb 矩形显示在一行中,因为即使它们嵌套在 中Obj,它们也会在内部委托给该行。

使用default属性意味着您不必手动指定它。当然,如果你不想这样,你甚至可以使用多个不同的占位符,例如,你可以有:

  property alias content: contentItem.children // this is a column of contents
  property alias control: buttons.children // this is a row of buttons
Run Code Online (Sandbox Code Playgroud)

请记住,如果不使用默认属性,则必须将对象指定为逗号分隔列表(如果它们是多个):

  Obj {
    content : [
      Rectangle {
        width: 10
        height: 10
        color: "red"
      },
      Rectangle {
        width: 10
        height: 10
        color: "green"
      },
      Rectangle {
        width: 10
        height: 10
        color: "blue"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

如果是单个对象则不需要,可以这样创建:

  Obj {
    content : Rectangle {
      width: 10
      height: 10
      color: "green"
    }
  }
Run Code Online (Sandbox Code Playgroud)

但您也可以使用单个目标,并让您的行在外部嵌套对象,这可以让您不必费心处理数组表示法,并为您提供更大的灵活性:

  Obj {
    content : Row {
      // bunch of stuff here
    }
  }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,content可以是一个简单的 located Item,它将用作占位符,就像弹出组件的情况一样。

最后,Loader如果您想指定内联组件,您还可以使用 a ,即未在专用 QML 文件中定义但使用该Component元素的组件。

  • 使用“默认属性别名”时,最好将别名设置为“data”而不是“children”。原因是“children”仅接受 Items,它不适用于“Timer”或其他非视觉对象。 (3认同)