how to create a scrollbar for rectangle in QML

2019-07-12 18:23发布

问题:

like the web pages,when content's high beyond the rectangle,there is a scrollbar. Is there anyone else who can help me? I have tried with listview,but I can't use it in a rectangle

回答1:

There is an example in the docs, how to use ScrollBar without a Flickable:

import QtQuick 2.7
import QtQuick.Controls 2.0

Rectangle {
    id: frame
    clip: true
    width: 160
    height: 160
    border.color: "black"
    anchors.centerIn: parent

    Text {
        id: content
        text: "ABC"
        font.pixelSize: 160
        x: -hbar.position * width
        y: -vbar.position * height
    }

    ScrollBar {
        id: vbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Vertical
        size: frame.height / content.height
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

    ScrollBar {
        id: hbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Horizontal
        size: frame.width / content.width
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }
}


回答2:

adding rectangle into flickable solved my problem

import QtQuick.Controls 2.5
import QtQuick.Controls.Material 2.5
import QtQuick 2.8
Item {
    id: item1
    visible: true
    width: 800
    height: 600
    ScrollView {
        id: frame
        clip: true
        anchors.fill: parent
        //other properties
        ScrollBar.vertical.policy: ScrollBar.AlwaysOn
        Flickable {
            contentHeight: 2000
            width: parent.width
            Rectangle {
                id : rectangle
                color: "#a7c4c6"
                radius: 6
                //visible: !busyIndicator.running
                anchors.fill: parent
            }
        }
    }
}