Sunday, March 25, 2012

The Most Basic Splitter Component Possible

The most basic splitter involves the top part of the area, the bottom part and the splitter in between. The splitter is a narrow rectangle with a MouseArea. drag.target:splitterRect makes the MouseArea to listen to drag events from splitter. drag.axis specifies along which axis the splitter can be dragged. When the splitter is dragged with the mouse along the Y axis, its Y position changes, triggering the onYChanged event, and the moveSplitterTo just recalculates the widths of top and bottom rectangles according to the current Y position of the splitter.

Additionally, if the splitter is not dragged, but clicked, the splitter collapses one of the frames. On start up, the first frame to be collapsed is chosen, and then, on each click, the other frame is collapsed, and the one that was collapsed is expanded.


Basic Splitter

One of the Frames is Collapsed

//Splitter component
import QtQuick 1.0

Item{
id: root
anchors.fill: parent
width: parent.width
height: parent.height
clip: true

property int splitterHeight: 10
property int maximizedRect : -1;

function moveSplitterTo(y)
{
if(y > 0 && y < parent.height - splitterHeight)
{
topRect.height = y;
bottomRect.height = parent.height - topRect.height - splitterHeight;
}
}

function maximizeRect(x)
{
topRect.height = x===0 ? parent.height - splitterHeight : 0
bottomRect.height = x===0 ? 0 : parent.height - splitterHeight
}

Rectangle{
id: topRect
width: parent.width
height: (parent.height-splitterHeight)/2
anchors.top: parent.top
color: "blue"
}

Rectangle {
id: splitterRect
width: parent.width
height: splitterHeight
color: "black"

anchors.top: topRect.bottom
anchors.bottom: bottomRect.top

property int tempY : splitterRect.y

onYChanged: {
moveSplitterTo(splitterRect.y);
}

BorderImage {
id: splitterBorder
anchors.fill: parent
source: "images/splitterBorder.png"
}

Image{
id: arrows
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
source: "images/splitterArrows.png"
}

MouseArea {
anchors.fill: parent
drag.axis: Drag.YAxis
drag.target: splitterRect

onClicked: {
maximizedRect = maximizedRect == 1 ? 0 : 1;
maximizeRect(maximizedRect);
}
}
}

Rectangle{
id:bottomRect
width: parent.width
height: (parent.height-splitterHeight)/2
anchors.bottom: parent.bottom
color: "red"
}
}

References

QML MouseArea Element
SplitterRow.qml by . Also posted on my website