How to scroll QML ScrollView to center?

2019-02-23 01:55发布

I have code like this:

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

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

标签: qt qml qtquick2
1条回答
再贱就再见
2楼-- · 2019-02-23 02:26

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
        }
    }
}
查看更多
登录 后发表回答