qtqmlflickable

How to predict a good position for snapping a flickable in QML


I have a flickable, which I want to snap to certain positions (which I compute in a specific way). I see two options:

  1. in movementEnded I snap to the nearest position to "contentX" with a number animation
  2. in flickEnded I snap to the nearest position to "contentX" with a number animation

Option 1 does not look good, the movement stops and afterwards the flickable starts moving again (the snapping positions are half a screen apart).

In Option 2 I find the choice of snap position difficult. If the user slides with a fast movement, I would prefer to snap to a position close to the position, where the movement would end, but that is hard to predict.

Here is example code for option 1:

NumberAnimation on contentY {
        id: yAnimation
        to: 0
        duration: 200
    }
onMovementEnded: {
       var index = Math.round(contentY / (itemHeight))
       yAnimation.to = index * itemHeight
       yAnimation.start()
}

Solution

  • In Option 2 I find the choice of snap position difficult. If the user slides with a fast movement, I would prefer to snap to a position close to the position, where the movement would end, but that is hard to predict.

    You have properties for horizontal and vertical velocity, so out of those you can calculate a compound velocity, have another

    property bool aboutToStop: horizontalVelocity + verticalVelocity < thresholdValue

    and

    onAboutToStopChanged: if (aboutToStop) playASnapAnimationToTheNearestItem()