如何在QML中为矩形创建滚动条

5

就像网页一样,当内容超出矩形框时,会出现滚动条。 有没有其他人可以帮助我? 我已经尝试过使用listview,但是我无法在矩形框中使用它。


可能会有所帮助,提供一些更详细的说明,并且可能还要附上您已尝试过的代码片段。 - wwkudu
请尝试使用ScrollView - folibis
2个回答

8

文档中有一个示例,介绍如何在没有Flickable的情况下使用ScrollBar

enter image description here

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
我认为这很酷,你可以在如此基础的项目上获得那种功能。 :) - Mitch
今天(2017年12月)这个应该能工作吗?因为我尝试了一下,它并没有工作。而且那两个QT页面也找不到了。 - s1n7ax
适用于Qt 5.9.3和Qt 5.10.0。我已经更新了链接,请为我工作。 - jpnurmi

5
将矩形添加到可滚动区域中解决了我的问题。
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
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接