QML输入控件: Dial基本用法与样式定制(1)
目录
前言
1. Dial控件基础介绍
1.1 核心属性
1.2 基本示例
2. 基本样式定制
2.1 代码示例
2.2 要点说明
2.3 运行效果
完整工程下载
前言
Dial(旋钮)控件是Qt Quick Controls模块中一个独特的圆形交互元素,它模拟了物理旋钮的行为,允许用户通过旋转手势来调整数值。这种控件在音频处理、参数调整、仪表盘等场景中非常有用。本文主要介绍Dial控件的基础用法与样式定制。
参考:Dial QML Type | Qt Quick Controls 6.8.3
1. Dial控件基础介绍
Dial控件提供了一个圆形旋钮界面,用户可以通过以下方式与之交互:
- 鼠标拖动旋转
- 触摸屏上的旋转手势
- 键盘方向键控制(需获得焦点)
1.1 核心属性
Dial控件包含以下关键属性:
- value:当前旋钮的值(范围由from和to决定)
- from:最小值(默认为0.0)
- to:最大值(默认为1.0)
- stepSize:步进值(调整时的最小单位)
- snapMode:对齐模式(是否自动对齐步进值)
- wrap:是否允许循环旋转
- inputMode:输入模式(圆形或水平/垂直)
1.2 基本示例
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("基本Dial示例")
Dial {
id: basicDial
anchors.centerIn: parent
width: 200
height: 200
from: 0
to: 100
value: 50
onValueChanged: {
console.log("当前值:", value.toFixed(1))
}
}
Text {
anchors.top: basicDial.bottom
anchors.horizontalCenter: basicDial.horizontalCenter
text: "当前值: " + basicDial.value.toFixed(1)
font.pixelSize: 16
}
}
这段代码用于展示一个基本的Dial控件和一个Text控件。以下是代码的简单总结:
- 在窗口中放置了一个Dial控件(basicDial),用于显示一个可调节的旋钮。
- Dial的范围是从0到100,默认值为50。
- 当Dial的值发生变化时,会在控制台输出当前值(保留一位小数)。
- 在Dial控件的下方放置了一个Text控件,用于实时显示Dial的当前值(保留一位小数)。
运行效果:
2. 基本样式定制
Dial控件的外观可以通过多种方式进行自定义。
2.1 代码示例
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("基本样式定制")
Dial {
id: styledDial
width: 150
height: 150
anchors.centerIn: parent
from: 0
to: 10
stepSize: 0.5
snapMode: Dial.SnapOnRelease
background: Rectangle {
implicitWidth: styledDial.width
implicitHeight: styledDial.height
color: "transparent"
border.color: "#21be2b"
border.width: 4
radius: width / 2
}
handle: Rectangle {
id: handleItem
width: 16
height: 16
color: styledDial.pressed ? "#17a81a" : "#21be2b"
radius: width / 2
antialiasing: true
// 计算内部半径:背景半径减去边框宽度和手柄半径
property real innerRadius: (styledDial.background.width / 2) - styledDial.background.border.width - (width / 2)
transform: [
// 将手柄移动到初始位置(顶部中点)
Translate {
x: styledDial.background.width / 2 - handleItem.width / 2
y: styledDial.background.height / 2 - handleItem.height / 2 - innerRadius
},
// 绕背景中心旋转
Rotation {
angle: styledDial.angle
origin.x: styledDial.background.width / 2
origin.y: styledDial.background.height / 2
}
]
}
}
}
这段代码定义了一个带有自定义样式的Dial控件,其旋钮(handle)围绕背景圆圈的中心旋转,并且通过计算内部半径确保旋钮始终位于圆圈内。
2.2 要点说明
圆圈(background):
使用一个Rectangle作为背景,设置其宽度和高度与Dial相同,边框颜色为#21be2b,边框宽度为4,半径为宽度的一半,使其呈现圆形。
旋钮(handle):
旋钮是一个Rectangle,宽度和高度均为16,颜色根据是否按下改变。
通过innerRadius属性计算旋钮的内部半径,确保旋钮始终在背景圆圈内。
使用Translate将旋钮移动到背景圆圈的顶部中点(初始位置),然后通过Rotation绕背景圆圈的中心旋转。
旋转原点:
旋转的原点设置为背景圆圈的中心(styledDial.background.width / 2 和 styledDial.background.height / 2),确保旋钮围绕背景圆圈的中心旋转。
Dial控件的属性:
from和to定义了Dial的值范围,stepSize定义了每次旋转的步长,snapMode设置为Dial.SnapOnRelease,表示值在释放时才会更新。
2.3 运行效果
完整工程下载
https://gitcode.com/u011186532/qml_demo/tree/main/qml_dial