你有两个方面需要考虑。直接来自文档:
只有一个 Item可以是 ScrollView 的直接子项,并且子项被隐式锚定以填充滚动视图。
因此,您不能拥有多个s Rectangle
,而只是一个用于所有 s 的容器Rectangle
(实际上是图像,如您的问题中所述)。
此外,应该再次从文档中指出:
子项的宽度和高度将用于定义内容区域的大小。
因此,您只需要一个孩子,ScrollView
并确保它从父母那里得到正确的尺寸。我会ColumnLayout
为此目的使用 a 。最终示例代码在这里:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0
import QtQuick.Layouts 1.1
ApplicationWindow{
id: appWindow
width: 200
height: 100
visible: true
ScrollView {
anchors.fill: parent
ColumnLayout { // unique child
spacing: 10
width: appWindow.width // ensure correct width
height: children.height // ensure correct height
// your children hereon...
Repeater {
model: 4
delegate: Rectangle {
Layout.alignment: Qt.AlignHCenter
width: 50
height: 50
color : "yellow"
}
}
}
}
}
编辑
根据 OP 的说法,提供的解决方案不能完全满足他的需求,这是非常合理的。尤其是:
- 如果窗口水平调整大小,则不显示水平滚动条
- 显示垂直滚动条后立即显示水平滚动条
这两个问题都与使用的方法有关。问题 1 是由 parentwidth
和ScrollView
width
: 之间的绑定引起的,因为 visiblewidth
总是等于 total width
,所以即使包含的项目大于窗口,也不会显示水平滚动。问题2是1的结果:由于width
等于应用程序,所以一旦添加了垂直滚动条,水平的也将添加以显示垂直滚动条覆盖的水平空间。
这两个问题都可以通过将width
绑定更改为等于包含的项目width
(解决问题 1)或等于(解决问题 2)width
的绑定来解决,正如另一个答案viewport
中所讨论的那样。最后,应移除锚定以避免绑定循环。这是一个按预期工作的完整示例:
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
ApplicationWindow{
id: appWindow
width: 200
height: 100
visible: true
ScrollView {
id: scroller
width: appWindow.width // NO ANCHORING TO AVOID binding loops!
height: appWindow.height
ColumnLayout { // <--- unique child
spacing: 10
width: Math.max(scroller.viewport.width, implicitWidth) // ensure correct width
height: children.height // ensure correct height
// your children hereon...
Repeater {
model: 3
delegate: Rectangle {
Layout.alignment: Qt.AlignHCenter
width: 150
height: 150
color : "yellow"
}
}
}
}
}
绑定到窗口的width
水平滚动不显示,即使包含的项目大于窗口