Search code examples
qmlqtquickcontrols

QML Rectangle Object coming in wrong place


I am just trying to create 4 rectangles with 3 next to each other and 4th one is below the 3rd rectangle and my qml looks like below

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Rectangle")

    Item{
        anchors.centerIn: parent
        Rectangle {
            id: firstRect
            width:50
            height:50
            color: "#ff0000"
        }
        Rectangle {
            id: secondRect
            width:firstRect.width
            height: firstRect.height
            color: "blue"
            //opacity: 0.5
            anchors.left: firstRect.right
        }
        Rectangle {
            id: thirdRect
            width:firstRect.width
            height: firstRect.height
            color: "green"
            //opacity: 0.5
            anchors.left: secondRect.right
        }
        Rectangle {
            id: fourthrect
            width:firstRect.width
            height: firstRect.height
            color: "green"
            //opacity: 0.5
            anchors.top: thirdRect.bottom
        }

    }
}

But i am getting the 4th rectangle below the first rectangle like below even though my anchor is thirdRect.Bottom what am i doing wrong enter image description here


Solution

  • Nearly there, you're close. Just need to anchor it horizontally under the third rectangle.

    Rectangle {
        id: fourthrect
        width:firstRect.width
        height: firstRect.height
        color: "green"
    
        anchors.top: thirdRect.bottom
        anchors.left: thirdRect.left     //  <-- this
    }
    

    Note that, assuming both the third and fourth rectangles have the same width, it's also possible to use anchors.right: thirdRect.right or anchors.horizontalCenter: thirdRect.horizontalCenter.

    Setting anchors.top: thirdRect.bottom will only anchor the item vertically, but not horizontally.