Marzanna
Marzanna

Reputation: 163

Attach scrollbar to ListView

I'm having an issue with ListView; it's too long and part of it appears outside the window, but I can't attach a scrollbar. I tried many combinations.

The problem probably lies in the height parameter, but if I remove it, ListView displays only the first entry.

Column{
    anchors.fill: parent
    Row{
        id: buttonsRow
        Button {
            text: "Open dump file"
            onClicked: fileDialog.visible = true
        }
        Button {
            text: "Copy raw data to clipboard"
        }
    }
    ListView{
        id: listView
        anchors.top: buttonsRow.bottom
        height: contentHeight
        //clip: true
        flickableDirection: Flickable.VerticalFlick
        boundsBehavior: Flickable.StopAtBounds
        interactive: true
        model: ListModel{
            id: listModel
        }
        delegate: MDelegate{}
    }
}

How do I make it scrollable?

Upvotes: 13

Views: 28548

Answers (3)

Sudarshan Deshmukh
Sudarshan Deshmukh

Reputation: 41

ScrollBar.vertical: ScrollBar {
    id: listView
    anchors.right: parent.right
    visible: listView.contentHeight > listView.height ? true : false
}

Upvotes: 2

WaltPurvis
WaltPurvis

Reputation: 1530

You need to include a ScrollBar component in your ListView, like this:

ListView { 
    id: listView
    ScrollBar.vertical: ScrollBar {
        active: true
    }
}

See Qt Documentation — Attaching ScrollBar to a Flickable.

Upvotes: 14

Mitch
Mitch

Reputation: 24386

Setting height to contentHeight is probably the issue. That would make the ListView as high as all of its item's heights combined. The scrollbar only works when the height of the view is less than the height of its contents.

Here's an approach that uses layouts instead:

import QtQuick 2.8
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.3

ApplicationWindow {
    width: 400
    height: 300
    visible: true

    ColumnLayout {
        anchors.fill: parent

        RowLayout {
            id: buttonsRow
            Button {
                text: "Open dump file"
            }
            Button {
                text: "Copy raw data to clipboard"
            }
        }

        ListView {
            id: listView
            flickableDirection: Flickable.VerticalFlick
            boundsBehavior: Flickable.StopAtBounds
            model: 100
            clip: true
            delegate: ItemDelegate {
                text: modelData
            }

            Layout.fillWidth: true
            Layout.fillHeight: true

            ScrollBar.vertical: ScrollBar {}
        }
    }
}

Upvotes: 10

Related Questions