Custom component with default content
-
Is there a way to give a custom component, default content, that can be optionally overridden? Using the default property seems to add to the list of children and not replace them.
Some pseudo code:
// customBox.qml Rectangle { id: root property alias content: root.children Text { id: defaultText text: "My default text" } }
// main.qml ... customBox { id: boxWithReplacedContent content: Rectangle { color: "blue" } customBox { id: boxWithDefaultContent } ...
What I would like is the Text object in "customBox" to be replaced by a blue rectangle in "boxWithReplacedContent". When I don't specify anything in the "content" property, like in "boxWithDefaultContent", I would like the "defaultText" object to be displayed. As it works now the blue rectangle will be added to the list of children rather than replacing the "defaultText" object.
Tim
-
Your example should be working, but you should add default sizing (with/height), so it will be visible. Also you might have to set width and height of your root rectangle to childrenRect.width / childrenRect.height. Depends on the usage.
customBox { id: boxWithReplacedContent content: Rectangle { width: 200 height: 100 color: "blue" } }
Rectangle { id: root width: childrenRect.width height: childrenRect.height property alias content: root.children Text { id: defaultText text: "My default text" } }
-
Your example should be working, but you should add default sizing (with/height), so it will be visible. Also you might have to set width and height of your root rectangle to childrenRect.width / childrenRect.height. Depends on the usage.
customBox { id: boxWithReplacedContent content: Rectangle { width: 200 height: 100 color: "blue" } }
Rectangle { id: root width: childrenRect.width height: childrenRect.height property alias content: root.children Text { id: defaultText text: "My default text" } }
@lemons Unfortunately, this still has the same problem where the blue rectangle is added to the list of children rather than replacing it. With the example you gave it appears to be working because the blue rectangle covers the default text. If you make the rectangle really small like 20 x 20 you will see them both on top of each other.
-
@lemons Unfortunately, this still has the same problem where the blue rectangle is added to the list of children rather than replacing it. With the example you gave it appears to be working because the blue rectangle covers the default text. If you make the rectangle really small like 20 x 20 you will see them both on top of each other.
@Tim-T yes you are right. this should work:
Rectangle { id: root property alias content: root.children width: childrenRect.width height: childrenRect.height Component { id: defaultComponent Text { text: "My default text" } } Component.onCompleted: { if (root.children.length === 0) defaultComponent.createObject(root) } }