使矩形宽度填充 ScrollView

Make rectangle width fill ScrollView

我正在尝试让 ScrollView 中的内容在 width 中扩展以适应屏幕。 ScrollView 锚定到主要 window。

例如,Rectangle:

ScrollView {
    anchors.fill: parent //mainWindow
    Rectangle {
        color: "light grey"
        height: 1000
        width: mainWindow.width
    }
}

但是当垂直滚动条出现时,它遮挡了Rectangle。我可以使用一个魔法常量来修复它:

width: mainWindow.width - 20

但是如果有人在他们的计算机上有更大的滚动条怎么办?当垂直滚动条不可见时,它还会在右侧留下一个难看的空白 space 。

有没有办法自动了解 ScrollView 中可用的 space?

无需明确调整滚动条。你可以让它填满整个可用的父 space 左右。如果你想指定边距:

ScrollView {
    id: scrollView
    anchors.fill: parent // mainWindow ?
    anchors.centerIn: parent // anchoring as asked
    anchors.margins: 20

    contentItem:
        Rectangle {
        id: rectScroll
        width: scrollView.viewport.width  // set as viewport
        height: 1000 // set to what you need
    }
}

原问题解决主要是因为Rectanglewidth属性设置为parent.parent.widthscrollView.viewport.width比较合适。后者肯定更好,只要滚动区域的精确视口 width 而不是父 width(通常不保证只包含此 ScrollView)。