I have a problem with centering QML objects in a ScrollView. I want to scroll the images and other QML elements and they should be centered. But they are always sticked to the top left angle.
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0
ApplicationWindow{
id: appWindow
width:Screen.width
height:Screen.height
visible: true
ScrollView {
anchors.fill: parent
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
width: 800
height: 800
color : "yellow"
}
}
}
You have two aspects to take in account. Directly from the docs:
So you could not have more than one
Rectangle, just a container for all theRectangles (which actually are images, as stated in your question).Moreover it should be noted, again from the docs, that:
Hence, you need only one child for the
ScrollViewand ensure that it takes the correct size from the parent. I would use aColumnLayoutfor the purpose. Final sample code here:EDIT
According to the OP the provided solution does not perfectly meet his needs and that's pretty reasonable. In particular:
Both the problems are related to the approach used. Problem 1 is caused by the binding between the parent
widthand theScrollViewwidth: since the visiblewidthis always equal to the totalwidth, no horizontal scroll is shown, even if the contained items are larger than the window. Problem 2 is a consequence of the 1: since thewidthis equal to application, as soon as a vertical scrollbar is added, the horizontal one is also added to show the horizontal space covered by the vertical scrollbar.Both the problems can be solved by changing the
widthbinding to be either equal to the contained itemswidth(to solve problem 1) or equal to thewidthof theviewport(solve problem 2), as also discussed in this other answer. Finally, anchoring should be removed to avoid binding loops. Here is a complete example working as expected:is bound to the window
widthhorizontal scrolls are not shown, even if contained items are larger than the window