English Български

How to make QML ListView align bottom-to-top

Normally QML ListView aligns all items at the top. New items get stacked on bottom. For some use cases like a conversations view you may want a different layout which starts at the bottom and also adds new items there.

This is how the ListView normally looks like:

The solution

The solution is easier than most people think. Rotation is the keyword.

  • Rotate the ListView by 180°
  • Also rotate the Delegate by 180° to get it back to normal direction. Don’t forget to give the delegate the whole width of ListView.view.width! Otherwise your items are right-aligned.
  • In order to get the newest items at the bottom, always insert the newest one at index 0 instead of appending it.

After doing these steps, your view should look like this:

The test code

  1. import QtQuick 1.0
  2.  
  3. Rectangle {
  4.     width: 300
  5.     height: 300
  6.  
  7.     Rectangle {
  8.         id: button
  9.         color: "red"
  10.  
  11.         anchors {
  12.             top: parent.top
  13.             left: parent.left
  14.             right: parent.right
  15.         }
  16.  
  17.         height: 20
  18.  
  19.         Text {
  20.             anchors.centerIn: parent
  21.             text: "Click me to add rows"
  22.         }
  23.  
  24.         MouseArea {
  25.             anchors.fill: parent
  26.             onClicked: {
  27.                 var row = {
  28.                     "id":listModel.count
  29.                 };
  30.  
  31.                 listModel.insert(0, row);
  32.             }
  33.         }
  34.     }
  35.  
  36.     ListView {
  37.         rotation: 180
  38.  
  39.         anchors {
  40.             top: button.bottom
  41.             bottom: parent.bottom
  42.             left: parent.left
  43.             right: parent.right
  44.         }
  45.  
  46.         model: ListModel {
  47.             id: listModel
  48.         }
  49.  
  50.         delegate: Rectangle {
  51.             rotation: 180
  52.             width: ListView.view.width
  53.             height: 20
  54.             color: "green"
  55.  
  56.             Text {
  57.                 anchors.centerIn: parent
  58.                 text: model.id
  59.             }
  60.         }
  61.     }
  62. }

Categories:

  • HowTo
  • snippets
  •