Search code examples
qmlqt5qtquick2qtquickcontrols

Make rectangle width fill ScrollView


I'm trying to get something in a ScrollView to expand in width to fit the screen. The ScrollView is anchored to the main window.

For example purposes, a Rectangle:

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

But when the vertical scrollbar appears, it obscures the Rectangle. I can sort of fix it by using a magic constant:

width: mainWindow.width - 20

But what if somebody has bigger scrollbars on their computer? Also it leaves an ugly empty space on the right when the vertical scrollbar is invisible.

Is there a way to automatically learn what the available space is inside of a ScrollView?


Solution

  • There is no need to explicitly adjust to scroll bar. You can just make it to fill the entire available parent space or so. And if you want specify margins:

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

    The original issue was solved mainly due to the width property of Rectangle set to parent.parent.width or scrollView.viewport.width as it is more adequate. The latter is definitely better, as long as the width of precisely viewport of scroll area and not the parent width (which in general not guaranteed to contain only this ScrollView).