How to make ScrollView clip only vertically?

3k views Asked by At

ScrollView clips all its contents to its size. Is it possible to make it work only for top and bottom but allow children to go out of parent's frame on the right and on the left?

2

There are 2 answers

3
derM - not here for BOT dreams On BEST ANSWER

I can only imagine one reason, why you don't set the ScrollView's width to a higher value (the contentItem's width).

To be able to do so, while not constraining the ScrollView in it's width, you can use a simple trick:

Item {
    id: limitedWidthItemToAnchorTo
    width: 200 // the width the ScrollView was supposed to have
    height: 400

    ScrollView {
        width: contentItem.width + __verticalScrollBar.width// Don't limit the width.
        height: 400 // Limit only the height.
        horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff // You don't need them.
        contentItem: Rectangle {
            width: 700 // This will set the ScrollViews width.
            height: 600 // The height will be clipped by the ScrollView. 
                        // You can scroll though.

            gradient: Gradient {
                GradientStop { position: 0; color: 'red' }
                GradientStop { position: 1; color: 'blue' }
            }
            border.width: 10
        }
    }
}

You'll wrap it in the Item, anchor to this, and you'll be good. Alternatively you could use masks, but this would be... more complicated.

Per se it is not possible to clip only horizontal or vertical, as the clipping is done using the Item's bounding box.

0
Paul-Sebastian Manole On

If what you want is to only scroll in one direction, then just set the width/height of the content item to the width/height of the ScrollView, using property bindings (because items inside ScrollView are reparented to ScrollView.contentItem). The below example will scroll only vertically. I've tested it, if you need confirmation that it actually works.

Item {
    ScrollView {
        id: scrollview1
        anchors.fill: parent
        anchors.margins: 20
        clip: true

        ColumnLayout {
            width: scrollview1.width
        }
    }
}