将滚动条添加到QML小部件(Qt 5.9.3)

时间:2018-01-10 13:50:40

标签: qt scroll qml scrollbar

如果需要,我需要添加垂直滚动到TextEdit并水平滚动到ListView并显示滚动条。两个小部件都必须填充其父布局提供的整个空间。我怎样才能做到这一点?例子没有帮助我。

ScrollableTextEdit

ColumnLayout {
    ...
    ScrollView {
        id: scroll_view
        Layout.fillWidth: true
        Layout.fillHeight: true
        ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
        ???
        Rectangle {
            border.color: 'gray'
            ???
            TextEdit {
                id: text_edit
                anchors.fill: parent
                textFormat: TextEdit.RichText
                wrapMode: TextEdit.Wrap
            }
        }
    }
}

ScrollableListView

ColumnLayout {
    ...
    ScrollView {
        id: scroll_view
        Layout.fillWidth: true
        Layout.fillHeight: true
        ScrollBar.vertical.policy: ScrollBar.AlwaysOff
        ???
        Rectangle {
            border.color: 'gray'
            ???
            ListView {
                id: list_view
                anchors.fill: parent
                ...
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您有太多项目图层。 ScrollView应该是TextEdit的直接父级。对于ListView,您可以使用附加的ScrollBar.horizo​​ntal属性来创建滚动条,而无需使用ScrollView。

见下面的例子

ApplicationWindow {
    visible: true
    x: 0
    y: 0
    width: 600
    height: 200
    id: root

    RowLayout
    {
        anchors.fill: parent
        anchors.margins: 20

        ColumnLayout
        {
            Label
            {
                text: "Example 1 (Vertical TextEdit)"
            }

            ScrollView
            {
                id: textEdit
                Layout.fillHeight: true
                Layout.fillWidth: true
                clip: true
                TextEdit
                {
                    text: "A very\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery\nvery long text"
                    anchors.fill: parent
                }
            }
        }


        ColumnLayout
        {
            Label
            {
                text: "Example 2 (Horizontal ListView)"
            }

            ListView
            {
                id: listView
                Layout.fillHeight: true
                Layout.fillWidth: true
                model: 10
                spacing: 10

                orientation: ListView.Horizontal
                ScrollBar.horizontal: ScrollBar {}

                delegate: Rectangle {
                    border.width: 1
                    height: parent.height
                    width: 100
                    Text {
                        anchors.centerIn: parent
                        text: index
                    }
                }
            }
        }

    }

}