1. 概述
Slider
是 QML 中用于通过滑动手柄选择值的控件。它允许用户在指定范围内选择一个值,常用于音量控制、亮度调节等场景。Slider
支持水平和垂直方向,可通过多种属性和信号进行自定义和交互。
2. 重要属性
-
from
:范围的起始值,默认为0.0
。 -
to
:范围的结束值,默认为1.0
。 -
value
:当前选中的值,默认为0.0
。 -
stepSize
:滑块的步长,用于控制滑块移动的最小单位。 -
orientation
:滑块的方向,可以是Qt.Horizontal
(默认)或Qt.Vertical
。 -
snapMode
:滑块的捕捉模式,可能的值包括:-
Slider.NoSnap
:不捕捉。 -
Slider.SnapAlways
:拖动时始终捕捉。 -
Slider.SnapOnRelease
:仅在释放时捕捉。
-
-
live
:是否在拖动滑块时实时更新value
属性,默认为true
。 -
position
:滑块的逻辑位置,范围为0.0 - 1.0
,表示滑块在整个轨道中的位置。 -
visualPosition
:滑块的视觉位置,与position
类似,但在 RTL(从右到左)布局中会反转。 -
handle
:滑块手柄的自定义项,可以设置为Item
类型的对象。 -
pressed
:表示滑块是否被按下,返回布尔值。 -
horizontal
:表示滑块是否为水平方向,返回布尔值。 -
vertical
:表示滑块是否为垂直方向,返回布尔值。 -
implicitHandleWidth
:滑块手柄的隐式宽度。 -
implicitHandleHeight
:滑块手柄的隐式高度。 -
touchDragThreshold
:触摸拖动的阈值,用于确定何时开始拖动滑块。
3. 重要方法
-
decrease()
:将滑块的值减少一个步长。 -
increase()
:将滑块的值增加一个步长。 -
valueAt(real position)
:根据给定的逻辑位置返回对应的值。
4. 重要信号
-
onValueChanged
:当滑块的值发生变化时触发。 -
moved()
:当滑块被移动时触发。
5. 常用枚举类型
-
orientation
:-
Qt.Horizontal
:水平方向。 -
Qt.Vertical
:垂直方向。
-
-
snapMode
:-
Slider.NoSnap
:不捕捉。 -
Slider.SnapAlways
:拖动时始终捕捉。 -
Slider.SnapOnRelease
:仅在释放时捕捉。
-
ApplicationWindow {
visible: true
width: 640
height: 480
Slider {
id: slider
anchors.centerIn: parent
width: 400
height: 40
from: 0
to: 100
stepSize: 1
value: 50
orientation: Qt.Horizontal
snapMode: Slider.SnapAlways
live: true
// 自定义背景
background: Rectangle {
width: slider.availableWidth
height: 10
radius: 5
color: "lightgray"
Rectangle {
width: slider.visualPosition * parent.width
height: parent.height
radius: 5
color: "blue"
}
}
// 自定义手柄
handle: Rectangle {
width: 30
height: 30
radius: 15
color: "white"
border.color: "black"
z: 1 // 确保手柄在背景之上
x: slider.visualPosition * (slider.availableWidth - width)
y: -(slider.height - height) / 2
}
onValueChanged: {
console.log("Slider value changed to " + value)
}
Component.onCompleted: {
console.log("Value at position 0.5 is " + slider.valueAt(0.5))
}
}
}
觉得有帮助的话,打赏一下呗。。
需要商务合作(定制程序)的欢迎私信!!