Abstract graphic with text reading ScrollBar

Creating QML Controls From Scratch: Implementing a ScrollBar

Chris Cortopassi

A seasoned engineer with 10+ years experience, Chris has expertise in desktop and embedded systems in larger, real-time multi-threaded applications, as well as experience using Qt-based software for complex projects within the motor control, telecommunications and civil engineering industries. 

By Chris Cortopassi | Wednesday, July 26, 2017

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:


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


ListView {


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

Have a question or add to the conversation: Log in Register