How to customize ScrollBar of ListView decorated by a custom ScrollView
-
I'm working on porting a project from Qt Quick Controls 1 to Qt Quick Controls 2. In the existing codebase, there's a custom ScrollView which is used in many places to decorate a ListView. With Quick Controls 1, this offered the ability to have custom styling for scroll bars everywhere the custom ScrollView was used via the ScrollViewStyle.
While porting this component, I've refactored the styling to work with Quick Controls 2. However, the scrollbars aren't appearing properly whenever I use this custom ScrollView. The scrollbars appear very small and aren't positioned correctly. It seems like I have to attach to the ScrollBar directly to the ListView to get them to work correctly.
Here's a minimal, reproducible example of what I mean:
A custom ScrollView
// MyScrollView.qml import QtQuick import QtQuick.Controls ScrollView { ScrollBar.vertical: ScrollBar { background: Rectangle { color: "black" radius: width/2 } contentItem: Rectangle { radius: width/2 color: "#73D0F9" implicitHeight: 8 implicitWidth: 6 } } }
main.qml
import QtQuick import QtQuick.Controls Window { width: 640 height: 480 visible: true title: qsTr("Hello World") MyScrollView { anchors.fill: parent ListView { model: 20 delegate: ItemDelegate { text: "Item " + index required property int index } } } }
Produces this:
If I instead attach the ScrollBar to the Listview, everything seems to work, but the default ScrollBar for the ScrollView overlaps with my custom one on the ListView:
//MyScrollView.qml import QtQuick import QtQuick.Controls ScrollView { }
main.qml
import QtQuick import QtQuick.Controls Window { width: 640 height: 480 visible: true title: qsTr("Hello World") MyScrollView { anchors.fill: parent ListView { ScrollBar.vertical: ScrollBar { background: Rectangle { color: "black" radius: width/2 } contentItem: Rectangle { implicitHeight: 6 implicitWidth: 8 radius: width/2 color: "#73D0F9" } } model: 20 delegate: ItemDelegate { text: "Item " + index required property int index } } } }
Produces this:
Why does the ScrollBar not get positioned or scaled correctly in the first example? Is it because the ScrollBar is parented to the ScrollView instead of the ListView? I'm not sure what I'm doing wrong
-
Try this code
import QtQuick 2.12 import QtQuick.Window 2.15 import QtQuick.Controls 2.13 Window { id:win1 visible:true width:900 height:300 ListView { id:list width: 100 height:parent.height model: 20 delegate: ItemDelegate { text: "Item " + index required property int index } ScrollBar.vertical: vsb } ScrollBar { id: vsb width: 16 anchors.left: list.right anchors.top: parent.top anchors.bottom: parent.bottom orientation: Qt.Vertical policy: ScrollBar.AlwaysOn } }