Qt Reference Documentation

Scalability: Using Anchors for Layouting

Files:

Using anchors for layouting items.

This example demonstrates how to use anchors for layouting items on orientation change. Similar logic could also be used for selecting layout for different resolutions.

Walkthrough

Firstly, we have three Box elements anchored to an initial layout.

 Box {
     id: greenBox
     width: ScalableUI.greenBoxWidth
     height: ScalableUI.greenBoxHeight
     anchors.top:  parent.top
     borderImage: "green.png"
 }

 Box {
     id: blueBox
     height: ScalableUI.blueBoxHeight
     anchors.top: parent.top
     anchors.left: greenBox.right
     anchors.right: parent.right
     borderImage: "blue.png"
 }

 Box {
     anchors.left: parent.left
     anchors.right: parent.right
     anchors.top: blueBox.bottom
     anchors.bottom: parent.bottom
     borderImage: "red.png"
 }

Secondly, we have layouts defined for portrait ("portraitLayout" state) and landscape ("landscapeLayout" state). The window.inPortrait is bound to the when property of the "portraitLayout" state. Similarly !window.inPortrait is bound to the when property of the "landscapeLayout" state. When orientation condition is met anchoring of the items is changed accordingly.

 State {
     name: "portraitLayout"
     when: window.inPortrait
     AnchorChanges {
         target: greenBox
         anchors.left: undefined
         anchors.horizontalCenter: parent.horizontalCenter
     }

     AnchorChanges {
         target: blueBox
         anchors.top: greenBox.bottom
         anchors.left: parent.left
         anchors.right: parent.right
     }
 },

 State {
     name: "landscapeLayout"
     when: !window.inPortrait
     AnchorChanges {
         target: greenBox
         anchors.left: parent.left
         anchors.horizontalCenter: undefined
     }

     AnchorChanges {
         target: blueBox
         anchors.top: parent.top
         anchors.left: greenBox.right
         anchors.right: parent.right
     }
 }