Slider Component

A slider is in general a rectangle with a handle. The handle can be dragged along one axis. The slider notifies others about the handle position. The handle position is normally converted in a value between 0 and 100.

Let’s see. For a horizontal slider, we need a rectangle for the slider and one for the handle. The handle needs to be inside the slider, so we make the handle a children of the slider rectangle. The handle shall only be dragged along the x-axis. The dragging shall stay inside the slider rectangle (drag minimum/maximum). And the slider value needs to reflect the handles position, adapted to the range of 0..100.

Here the file Slider.qml

import Qt 4.6

Rectangle {
  id: slider; 
  width: 320; height: 40; 
  anchors.centerIn: parent
  property int value: Math.round(handle.x*100/(slider.width-handle.width))
  color: "green"
  Rectangle {
    id: handle; width: 40; height: 40
    color: "red"
    MouseRegion {
      anchors.fill: parent parent; drag.axis: "XAxis"
      drag.minimumX: 0; drag.maximumX: slider.width - handle.width

The interesting aspect here is the usage of drag.

This is how you would use this slider (Slider.qml) components:

import Qt 4.6

Rectangle {
  width: 200; height: 200
  Slider {
    width: 120
    anchors.centerIn: parent

The output looks like this:

You can drag the red smaller rectangle along the x-axis of the larger rectangle.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s