Qt的QML有许多小部件,您可以在其中实例化该小部件,然后为它提供一个Component实例供其显示和使用。
例如,Popup
widget的用法如下:
suppressAggFuncInHeader : true;
我自己该怎么做?如何编写一个自定义QML Component,它将一个子Component实例放入我的树下?
如果我有一个愚蠢的组件,例如:
npm install -s socket.io
npm install -g xxxxxxx
,其用法类似于:
Popup { // <-- Parent Component
Rectangle { // <-- Child Component
width: 100;
height: 100;
color: 'red';
}
}
我可以将// 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?
}
实例化或移动为Parent {
Text { text: 'hello world!' }
}
的子代的语法或机制是什么?
答案 0 :(得分:2)
哇,这真是令人困惑,但如果我理解正确的话,您实际上希望孩子自动重定向到其他对象。这是可能的,例如:
// Obj.qml
Rectangle {
width: 50
height: 50
default property alias content: row.children
Row {
id: row
}
}
然后:
Obj {
Rectangle {
width: 10
height: 10
color: "red"
}
Rectangle {
width: 10
height: 10
color: "green"
}
Rectangle {
width: 10
height: 10
color: "blue"
}
}
结果是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
请记住,如果不使用默认属性,则在多个对象的情况下,必须将这些对象指定为以逗号分隔的列表:
Obj {
content : [
Rectangle {
width: 10
height: 10
color: "red"
},
Rectangle {
width: 10
height: 10
color: "green"
},
Rectangle {
width: 10
height: 10
color: "blue"
}
]
}
如果它是单个对象,则没有必要,可以这样创建:
Obj {
content : Rectangle {
width: 10
height: 10
color: "green"
}
}
但是您也可以使用单个目标,并使行在外部嵌套对象,这样可以省去麻烦使用数组表示法并为您提供更大的灵活性:
Obj {
content : Row {
// bunch of stuff here
}
}
在这种情况下,content
可以是一个简单放置的Item
,它将用作占位符,就像弹出组件一样。
最后,如果要指定内联组件,也可以使用Loader
,该内联组件不是在专用QML文件中定义的,而是使用Component
元素。