How to scroll QML ScrollView to center?

fhdnsYa picture fhdnsYa · May 20, 2015 · Viewed 8.5k times · Source

I have code like this:

ScrollView {
    Image {
        source: "..."
    }
}

Image is higher than the ScrollView. How can I scroll the latter to the center of Image element?

Answer

BaCaRoZzo picture BaCaRoZzo · May 21, 2015

Despite the appearence, ScrollView is tightly related to Flickable. Indeed, Flickable is used to control the visible area. Such an Item is available as the (readonly) property flickableItem. Flickable has the contentX and contentY properties to control the current visible area. These properties can be combined with the width and height of the ScrollView to position the visible area exactly at the center. Typically you have:

flickableItem.contentY = flickableItem.contentHeight / 2 - height / 2
flickableItem.contentX = flickableItem.contentWidth / 2 - width / 2

The difference is necessary since the first calls just moves the center to the top left point of the visible area (where contentX/contentY are located).

Here is a complete example with an Image as main child of the ScrollView.

Disclaimer: In the simple scenario proposed by the example, with a remotelly loaded image, sizes can still be unset when onCompleted is called, resulting in a centering code that doesn't work. By setting widths and heigths directly into code the problem is avoided. In a real scenario such detail should be unnecessary.

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.2

Window {
    id: main
    visible: true
    width: 600; height: 350

    ScrollView {
        id: ss
        width: 600
        height: 350

        Image {
            id: name
            width: 900
            height: 600
            source: "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg"
        }

        Component.onCompleted: {
            flickableItem.contentY = flickableItem.contentHeight / 2 - height / 2
            flickableItem.contentX = flickableItem.contentWidth / 2 - width / 2
        }
    }
}