如何将 QML ScrollView 滚动到中心? [英] How to scroll QML ScrollView to center?

查看:450
本文介绍了如何将 QML ScrollView 滚动到中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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

Image 高于 ScrollView.如何将后者滚动到 Image 元素的中心?

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

推荐答案

尽管出现,ScrollViewFlickable 紧密相关.事实上,Flickable 是用来控制可见区域的.这样的 Item 可用作 (readonly) 属性 flickableItem.Flickable 具有 contentXcontentY 属性来控制当前可见区域.这些属性可以与 ScrollViewwidthheight 结合使用,以将可见区域精确定位在中心.通常您有:

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

差异是必要的,因为第一次调用只是将中心移动到可见区域的左上点(其中contentX/contentY位于).

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).

这是一个完整的示例,其中 Image 作为 ScrollView 的主要子元素.

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

免责声明:在示例提出的简单场景中,使用远程加载的图像,onCompleted 被调用,导致居中代码不起作用.通过将宽度和高度直接设置到代码中,可以避免该问题.在实际场景中,这样的细节应该是不必要的.

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
        }
    }
}

这篇关于如何将 QML ScrollView 滚动到中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆