如何将 QML ScrollView 滚动到中心? [英] How to scroll QML ScrollView to center?
问题描述
我有这样的代码:
ScrollView {
Image {
source: "..."
}
}
Image
高于 ScrollView
.如何将后者滚动到 Image
元素的中心?
Image
is higher than the ScrollView
. How can I scroll the latter to the center of Image
element?
推荐答案
尽管出现,ScrollView
与 Flickable
紧密相关.事实上,Flickable
是用来控制可见区域的.这样的 Item
可用作 (readonly
) 属性 flickableItem
.Flickable
具有 contentX
和 contentY
属性来控制当前可见区域.这些属性可以与 ScrollView
的 width
和 height
结合使用,以将可见区域精确定位在中心.通常您有:
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屋!