Search code examples
qtqmlqtquick2

QML page content not centered in stackview when page is resized


I have just created a new project selecting the default Qt Quick Application - Stack template.

Running the project as is (on a desktop) shows some problem.

1- At first the page contents (which is a simple text) is centered in the window/page as expected due to layaout:

anchors.centerIn: parent

2- but if I resize the window the "TEXT" position is not changed!!!

3- if i preview just the page via qmlscene and resize it, the contents are corectly repositioned in the center as expected.

Q: How can i solve this problem and force the text to be always displayed in the center of the page?

Platform info:

  • Qt: 5.12.1
  • Qt creator: 4.8.1
  • OS: win10

(I did not provide the code, since i used the default code generated by Qt creator for Qt quick stack app)

Thanks in advance

1- As mentioned above, the single pages content is layed out correctly when the page is resized (testing the page standalone via qmlscene)

2- i tried to handle the resize events but i couldn't

onWidthChanged: {anchors.centerIn: parent}

the erros:

  • expected token ','
  • Javascript blocks are not supported in qt quick ui form

I tried to do this from the main.qml file but i couldn't


Solution

  • The HomeForm.ui.qml, Page1Form.ui.qml and Page2Form.ui.qml all set:

        width: 600
        height: 400
    

    This causes those pages to not follow resizes the StackView. Unfortunately, those lines are needed when editing those pages in the Designer so you cannot remove them. However, if you add the anchors.fill: parent to those pages:

        width: 600 // used by the designer
        height: 400 // used by the designer
        anchors.fill: parent // used by the application
    

    it will cause those pages to follow the StackView geometry. Since the StackView already has anchors.fill: parent means the StackView will resize when the app resizes taking along with the child pages. You should find the centered text will now follow the new center during those resizes.