QML 的
SplitView
是一个用于创建可分割视图的组件,它允许用户通过拖动分隔条来调整不同视图部分的大小。SplitView
非常适合用于创建如侧边栏、双栏布局等场景,其中一部分内容需要占据固定或可变的空间,而另一部分则可以根据用户的需要进行调整。QML SplitView 组件的基本结构
SplitView
通常包含至少两个子视图,它们通过分隔条进行分隔。用户可以通过拖动分隔条来调整各个子视图的大小。QML SplitView 的属性
orientation
: 设定分割条的方向,可以是Qt.Horizontal
或Qt.Vertical
。QML SplitView 的信号
handleMoved
: 当分割条被移动时触发。
QML SplitView 代码使用示例
下面是一个简单的
SplitView
使用示例,展示了如何在 QML 中使用它来创建一个水平和垂直分割的布局:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
Window
{
visible: true
width: 640
height: 480
title: qsTr("Test Example")
SplitView
{
id: splitView
anchors{
top: parent.top
left:parent.left
right: parent.right
}
height:parent.height/2
orientation: Qt.Horizontal
//设置分割线样式
handleDelegate : Rectangle{
width: 7
color: "gray"
}
// 第一个视图部分
Rectangle
{
width: parent.width / 2
color: "lightblue"
Text {
text: "Left Pane"
anchors.centerIn: parent
}
}
// 分隔条
// SplitView 自动处理分隔条,无需显式创建
// 第二个视图部分
Rectangle
{
width: parent.width / 2
color: "lightgreen"
Text {
text: "Right Pane"
anchors.centerIn: parent
}
}
}
// 垂直分割的 SplitView 示例
SplitView {
id: verticalSplitView
anchors.top: splitView.bottom
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.right: parent.right
orientation: Qt.Vertical
// 上部视图部分
Rectangle {
height: parent.height / 2
color: "pink"
Text {
text: "Top Pane"
anchors.centerIn: parent
}
}
// 下部视图部分
Rectangle {
height: parent.height / 2
color: "yellow"
Text {
text: "Bottom Pane"
anchors.centerIn: parent
}
}
}
}
运行结果:
在这个示例中,我们创建了两个
SplitView
:一个水平分割的和一个垂直分割的。每个SplitView
都包含两个Rectangle
子项,它们通过SplitView
的分隔条进行分隔。你可以通过拖动分隔条来调整各个部分的大小。注意
SplitView
是 Qt Quick Controls 1.4 的一部分,因此你需要确保你的项目包含了相应的模块。SplitView
的子项可以是任何 QML 元素,不仅仅是Rectangle
。你可以根据需要放置任何类型的视图或组件。- 你可以通过连接
handleMoved
信号来响应用户对分隔条的移动操作,并执行自定义的逻辑。