Creating QML Controls From Scratch: Implementing a ScrollBar

By Chris Cortopassi

Continuing our QML Controls from Scratch series, this time we will implement a vertical ScrollBar, which is the vertical line segment you often see on the right of a touch user interface as you scroll vertically through a list of items. ScrollBar is quite a bit different than the other controls in this series as it can't be run stand-alone in qmlscene. Rather, it is designed to be a direct child of a ListView or GridView (the ScrollBar's parent). The ScrollBar's position (y) and height are computed with a bit of math, based proportions of Flickable's contentHeight and contentY, as illustrated below.

You can see an example of ScrollBar on the right side of test.qml if you resize qmlscene to a short enough height:

ScrollBar.qml

import QtQuick 2.0

Rectangle { // ScrollBar to be placed as a direct child of a ListView or GridView (ScrollBar won't run by itself and gives errors)
    color: 'black'
    width: 0.01 * parent.width;  radius: width / 2 // size controlled by width
    anchors{right: parent.right;  margins: radius}
   
    height:  Math.max(parent.height / parent.contentHeight * parent.height - 2 * radius, 20) // minimum height for large lists
    y:       parent.contentY / parent.contentHeight * parent.height + radius
    visible: parent.height   < parent.contentHeight
}

test.qml

ListView {
    ...
   
    ScrollBar{}
}

Summary

In this post, we created ScrollBar. Next up: ProgressBar. The source code can be downloaded here.

Have a question or want to add to the conversation?

You must be logged in to continue.

Log in Register