Solved Anchoring Items of a Component Within Loader Obeject
-
I am trying to use a loader object to dynamically load different components I have defined in QML (within the same file). I am finding that I am not able to use anchors in the way I think that I should be able to:
i.e. simple example, column with 3 rectangles, this works fine in my QML window, as expected, the 3 rectangles are horizontally centered in the parent window:
Column { anchors.horizontalCenter: parent.horizontalCenter spacing : 50 Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } }
However, if I encapsulate this as a component, and use a Loader to load an instance of it, they are no longer centered, the anchor statement is ignored:
Loader { id: myCoolLoader anchors.fill: parent sourceComponent: myCoolItem } Component { id: myCoolItem Column { anchors.horizontalCenter: parent.horizontalCenter spacing : 50 Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } } }
How can I make this work or what am I doing wrong here? Maybe since a loader is dynamic the child isn't able to reference the parent the same way? I also tried directly using id "myCoolLoader" rather than parent.
-
Hi @kengineer , you need to anchor the Loader, so instead of filling it you need to anchor the loader horizontal.
Here is the sample code:-
Loader { id: myCoolLoader //anchors.fill: parent anchors.horizontalCenter: parent.horizontalCenter sourceComponent: myCoolItem }
-
@kengineer hi
see this https://doc.qt.io/qt-5/qml-qtquick-loader.html#loader-sizing-behavioryou have to set the horizontalCenter of your loader and it will apply to loaded item
Loader { id: myCoolLoader anchors.horizontalCenter: parent.horizontalCenter sourceComponent: myCoolItem } Component { id: myCoolItem Column { spacing : 50 Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } Rectangle { color: "Red" width: 50 height: 50 } } }