How to make rectangle height fill ScrollView

2019-07-15 01:41发布

I have the following QML code:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

Window {
    id: win
    width: 1024
    height: 768
    visible: true

    ScrollView {
        id:scrollView
        anchors.fill: parent
        Rectangle{
            id:rect
            z:5
            color:"red"
            width: 2048
            height: win.height
            border{
                color: "black"
                width: 2
            }
        }
    }
}

In this code the larger Rectangle makes the horizontal scrollbar correctly appear. However, since the scrollbar takes some height from the window, the vertical scrollbar appears too.

How can I make the Rectangle fill only available space in my ScrollView so that vertical scrollbar won't show up? Using something like win.height - <someNumber> is not acceptable. Adding verticalScrollBarPolicy: Qt.ScrollBarAlwaysOff is also not acceptable cause it hides some content on bottom of rect.

1条回答
唯我独甜
2楼-- · 2019-07-15 02:05

Generally speaking ScrollView is not meant for such usage. It is more a container to lay out items and have them shown through the provided scrollbar. Binding loops can pop here and there if bindings are not properly set. Also Flickable + a custom scrollbar (e.g. the ones available here) can perfectly fit your needs.

That said, viewport property provides the desired (cross-platform) workaround for the problem. The documentation states:

The viewport determines the current "window" on the contentItem. In other words, it clips it and the size of the viewport tells you how much of the content area is visible.

Hence the height of the child Item can be set according to the height of the viewport. A final simple example with an Image (cute kitty incoming) would look like this:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

Window {
    id: win
    width: 300
    height: 300
    visible: true

    ScrollView {
        id:scrollView
        anchors.fill: parent

        Image{
            height: scrollView.viewport.height
            source: "http://c1.staticflickr.com/9/8582/16489458700_c9d82954b7_z.jpg"
        }
    }
}

enter image description here

查看更多
登录 后发表回答