What's wrong with centering component not from the main.qml [SOLVED]



  • I'm trying to draw rectangle in the center of the document, but can do that only in main.qml, because drawing rectangle in any other draws it on the incorrect position. I have the following main.qml document:

    ApplicationWindow {
        id: root
        width: 1080; height: 1920
    
        Rectangle {
            width: 250; height: 250
            color: "cyan"
            anchors {
                horizontalCenter: parent.horizontalCenter
                verticalCenter: parent.verticalCenter
            }
        }
    
        Button {
            id: myButton
        }
        Loader {
            id: pageLoader
        }
        MouseArea {
            anchors.fill: myButton
            onClicked: pageLoader.source = "Settings.qml"
        }    
    }
    

    This works just fine:

    alt text

    But Settings.qml inserts rectangle in the wrong location on the screen. Is it because qml was loaded from the Loader? I don't know any reasons why it is the way it is, but practice shows that rectangle from the Settings.qml is drawn incorrectly despite the fact that both qmls have the same anchors-positioning code. Here's my Settings.qml:

    Item {
        id: myItem
        width: 1080
        height: 1920
    
        Rectangle {
            id: myRect
            width: 250
            height: 250
            color: "red"
    
            anchors {
                horizontalCenter: parent.horizontalCenter
                verticalCenter:  parent.verticalCenter
            }
        }
    }
    

    And the result (after myButton from the main.qml was pressed) is:

    alt text

    Whether it is somehow relevant to Loader or not?


  • Moderators

    Hi @sosun,

    Whether it is somehow relevant to Loader or not?

    Yes indeed it is related to the Loader. You must specify position to the Loader. To center the red rectangle you will need to center the Loader itself. Try anchoring the Loader to parent's center.

    Loader {
        id: pageLoader
        anchors.centerIn: parent
    }
    


  • @p3c0 Yeah, it works! Thank you ;)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.