Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Anchors in a loaded file are not working correct - why?



  • Hello,

    I have a small problem with anchors.
    I do load pages via a loader to a StackLayout.
    Somehow the size of the parent (StackLayout) it not populated correctly to the loaded file, so that e.g. in the following example the button is not horizontally centerted.

    Why is that and how can I solve that?

    Thank you very much!

    0_1532076345529_problem.JPG

    main.qml

    import QtQuick.Controls 2.2
    import QtQuick.Layouts 1.3
    import QtQuick 2.7
    
    
    ApplicationWindow {
        id: root
        width: 500
        height: 800
        title: qsTr("Settings")
        visible: true
    
    
        header: TabBar {
            id: bar
            width: parent.width
            TabButton {
                text: qsTr("Home")
            }
        }
    
    
        StackLayout {
            anchors.fill: parent
            currentIndex: bar.currentIndex
    
            Item {
                id: envi
                anchors.centerIn: parent
                Loader {
                    source: "qrc:/Page1.qml"
                }
            }
        }
    }
    

    page1.qml:

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.3
    
    Item {
        anchors.centerIn: parent
    
        Button {
            id: buttonStop
            text: qsTr("Stop")
            font.pixelSize: 18
            anchors.top: parent.top
            anchors.topMargin: 50
            anchors.horizontalCenter: parent.horizontalCenter
        }
    }
    
    


  • @robro
    You need to give your Items some dimensions: e.g. the parent of Button is an Item with zero dimensions...

    Furthermore, in

    StackLayout {
            anchors.fill: parent
            currentIndex: bar.currentIndex
    
            Item {
                id: envi
                anchors.centerIn: parent
               ....
          }
    

    , the line anchors.centerIn: parent produces the following warning:

    qrc:/main.qml:31:9: QML QQuickItem: Detected anchors on an item that is managed by a layout.
    This is undefined behavior; use Layout.alignment instead.
    

    so, you can use instead: e.g.

    Item {
                id: envi
    
                //anchors.centerIn: parent //undefined behavior
                Layout.alignment: Qt.AlignVCenter | Qt.AlignHCenter
    
                width: root.width
                height: root.height
               ...
    }
    

    Also give Item in page1.qml some dimensions...



  • Thanks a lot, especially for the additional information :-)


Log in to reply