QML: What does the "x" property exactly do and what's the difference with anchors.leftMargin/rightMargin in a ListView?

Viewed 246

I tried to add a margin to a ListView element using anchors.leftMargin expecting it would create a margin between the screen border and the beginning of the list, but it didn't work at all. Using x instead solved the problem. Here is the code:

   ListView {
    id: list
    width: parent.width - sideMargin
    x: sideMargin //works
    anchors.leftMargin: sideMargin //doesn't work
    orientation: ListView.Horizontal
    focus: true
    spacing: 16
    //...
   }

So now I am wondering when to use these properties, because reading the docs is not enough for me to understand when to use one or the other.

1 Answers

Items in QML/QtQuick can be positioned and sized in 3 different ways:

  1. Freely using the x and y properties for position and the width and height properties for the size. See: https://doc.qt.io/qt-5/qml-qtquick-item.html#x-prop for more information.

    ListView {
        id: list
        width: parent.width - sideMargin
        x: sideMargin
        y: topMargin
    }
    
  2. Using Layouts, or more generally containers, such as ColumnLayout. All the work is done by the layout and you don't have to do anything, but you can still provide tips to the container.

  3. Using anchors. This is done through the anchors properties of each Item. This works by attaching (anchoring) Items against each other.

    ListView {
        id: list
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.leftMargin: sideMargin
    }
    

Note: Do not mix these 3 ways on a single Item as you can create conflicts or have unexpected results. In your case you are using method 3 for setting the margin without setting a position and method 1 for setting the width and thus it does not work.

Related