下面是一个完整的档位指示器组件实现,包含20个横向排列的竖直矩形,可以通过数值控制显示的档位数量,并有默认的白色底层指示器。
GearIndicator .qml
import QtQuick 2.12
import QtQuick.Controls 2.12
Item {
id: gearIndicator
width: 400
height: 60
// 属性
property int gearCount: 20 // 总档位数
property int currentGear: 0 // 当前档位(0-20)
property color activeColor: "green" // 激活档位颜色
property color baseColor: "white" // 基础档位颜色
// 底层白色档位指示器(默认显示)
Row {
id: baseGears
anchors.fill: parent
spacing: 2
Repeater {
model: gearCount
Rectangle {
width: (parent.width - (gearCount-1)*parent.spacing) / gearCount
height: parent.height
color: baseColor
opacity: 0.3
radius: 2
// 档位数字标签
Text {
text: index + 1
anchors.centerIn: parent
font.pixelSize: 10
color: "black"
}
}
}
}
// 上层绿色档位指示器(根据currentGear显示)
Row {
id: activeGears
anchors.fill: parent
spacing: 2
Repeater {
model: currentGear
Rectangle {
width: (parent.width - (gearCount-1)*parent.spacing) / gearCount
height: parent.height
color: activeColor
radius: 2
// 档位数字标签
Text {
text: index + 1
anchors.centerIn: parent
font.pixelSize: 10
color: "white"
}
}
}
}
// 当前档位文本显示
Text {
anchors.top: parent.bottom
anchors.topMargin: 5
anchors.horizontalCenter: parent.horizontalCenter
text: "当前档位: " + currentGear
font.pixelSize: 14
color: "white"
}
}
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQml 2.12
import QtQuick.Layouts 1.12
import "./image"
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
// Main.qml
Window {
visible: true
width: 800
height: 600
title: "档位指示器演示"
color: "#333"
Column {
anchors.centerIn: parent
spacing: 30
// 档位指示器组件
GearIndicator {
id: gearIndicator
width: 600
currentGear: gearSlider.value
}
// 控制滑块
Slider {
id: gearSlider
width: 500
value: 1
minimumValue:0
maximumValue:20
stepSize: 1
}
// 当前档位显示
Text {
text: "当前档位: " + gearSlider.value
font.pixelSize: 24
color: "white"
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
组件属性说明
属性名 | 类型 | 默认值 | 说明 |
---|---|---|---|
gearCount | int | 20 | 总档位数 |
currentGear | int | 0 | 当前档位(0-20) |
activeColor | color | "green" | 激活档位颜色 |
baseColor | color | "white" | 基础档位颜色 |
自定义样式
你可以通过修改以下属性来自定义外观:
GearIndicator {
activeColor: "red" // 改为红色档位指示
baseColor: "#ccc" // 改为灰色基础指示
height: 80 // 增加高度
}
实现特点
-
双层设计:白色底层始终显示20个档位,绿色上层显示当前档位
-
自动布局:根据组件宽度自动计算每个矩形宽度
-
响应式:currentGear属性变化时自动更新显示
-
可定制:颜色、大小等均可自定义
这个组件可以方便地集成到任何QML界面中,通过简单的属性绑定即可实现档位指示功能。