利用QML 的Tumbler实现时间选择器的功能。Tumbler在这里介绍的是QtQuick.Extras下面的。(QtQuick.Controls
中也有一个,但是略微不同)。
在此介绍Tumbler的样式修改以及数值修改、获取功能。
通过Tumbler的style属性实现。 Qt提供了TumblerStyle来实现属性的修改。
具体源码如下:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Extras 1.4
import QtQuick.Controls.Styles 1.4
//import QtQuick.Controls 2.3 //不能和QtQuick.Extras一起用
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Tumbler")
//color: "black"
function changeValues()
{
var index1 = Math.random()*100%6;
var index2 = Math.random()*100%12;
var index3 = Math.random()*100%12;
thumberp.setCurrentIndexAt(0,index1,1000);
thumberp.setCurrentIndexAt(1,index2,1000);
thumberp.setCurrentIndexAt(2,index3,1000);
}
function getValues()
{
var index = thumberp.currentIndexAt(0);
var cindex = thumberp.getColumn(0).model[index];
index = thumberp.currentIndexAt(1);
var cindex1 = thumberp.getColumn(1).model[index];
index = thumberp.currentIndexAt(2);
var cindex2 = thumberp.getColumn(2).model[index];
valuetext.text = "" + cindex+ " "+ cindex1 + " " + cindex2
}
RowLayout {
Rectangle {
width: 100;height: 30
color: "#00aadd"
Text {
anchors.centerIn: parent
text: "修改值"
}
MouseArea {
anchors.fill: parent;
onClicked: changeValues()
}
}
Rectangle {
width: 100;height: 30
color: "#00aadd"
Text {
id : valuetext
anchors.centerIn: parent
text: "获取值"
}
MouseArea {
anchors.fill: parent;
onClicked: getValues()
}
}
}
property var years: [2015,2016,2017,2018,2019,2020]
property var mouths: [1,2,3,4,5,6,7,8,9,10,11,12]
property var days: [1,2,3,4,5,6,7,8,9,10,11,12]
Tumbler {
id : thumberp
anchors.centerIn: parent
TumblerColumn {
model: years
width: 100
}
TumblerColumn {
model: mouths
width: 100
}
TumblerColumn {
model: days
width: 100
}
style: TumblerStyle{
id : styleData;
//外面的边框
frame : Rectangle{
// implicitWidth : 2
color: "green"
opacity: 0.6
}
//背景色设置
background: Rectangle{
color: "yellow"
}
foreground: Rectangle{
color: "black"
opacity: 0.3
gradient: Gradient {
GradientStop { position: 0.2; color: "lightsteelblue" }
GradientStop { position: 0.5; color: "blue" }
GradientStop { position: 0.8; color: "lightsteelblue" }
}
}
delegate : Rectangle{
width: 120
height: thumberp.height/3
color: "black"
Text {
anchors.centerIn: parent
text: styleData.value
opacity: 0.4 + Math.max(0, 1 - Math.abs(styleData.displacement)) * 0.6
color: "white"
font.pointSize: 15
}
}
//highlight 与delegate 有冲突,没有起到作用
highlight: Rectangle{
width: thumberp.width/3;
height: 40
color: "red"
}
}
}
}