使用QtQuick如何制作带有冷却效果的按钮
在很多游戏里,一个技能释放之后,需要一段时间冷却,然后才可以继续使用,在我做的小游戏《抗战》中也需要类似的功能,比如炮击、空袭、补给,那么在QML中如何实现这个效果呢?
分析一下整个过程:点击按钮后,按钮进入无效状态,然后背景出现某种冷却的效果,当冷却效果结束后,再置按钮有效。按钮一般是圆形的,有文字。
简单分析之后,“如何制作带有冷却效果的按钮”可以分解为两个小问题:
1 如果绘制圆形按钮?
2 如何连续按钮背景颜色?
1 如何绘制圆形按钮?
开始还是不习惯QML的编程思路,对着文档找Button的属性,找不到任何线索,后来看到了ButtonStyle,在Rectangle类型中有radius,用于绘制圆角矩形,而ButtonStyle可以设置为Rectangle,将Button的高和宽这是为相同的值,再将Rectangle::radius设置为按钮宽度的一半,这时绘制的按钮就是圆形的。
2 如何连续按钮背景颜色?
在Rectangle中有梯度属性gradient,可以设置背景颜色渐变过程。根据这个属性,设置三个GradientStop对象A、B、C,A的位置在0.0,颜色”grey”,C的位置在1.0,颜色"#ccc",关键就在B,B的颜色与A一致为”grey”,然后位置由1.0变到0.0,这样效果就是一个从下往上完成冷却的效果。
顺带还有一个问题:改为原型按钮后,默认字体很小,不好看,这就是第三个问题。
3 如何设置Button字体大小?
还是使用style,使用Text设置ButtonStyle::label属性,可以改变文字大小。
最终的效果是这样子的
代码如下:
// 说明:带有冷却效果的按钮组件
// 作者:陶赫 邮箱:taohe_0@163.com ,博客:http://blog.csdn.net/taohe_0
// 时间:20170225
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
Button
{
id : buttonSelf
height: width
// 冷却属性
property bool chillDown: false
property int chillDownDuration : 3000
style: ButtonStyle
{
label: Text
{
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pointSize: 20
text: control.text
}
// 定义背景,实现冷却效果
background: Rectangle
{
implicitWidth: 100
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "#888"
// 调整圆角,使按钮看起来是圆形
radius: width / 2
// 冷却效果有三个梯度对象实现,两端固定,中间的GradientStop由1.0端移动到0.0端就能表现出冷却的过程
gradient: Gradient
{
property double gradientPos: 1.0
GradientStop { position: 0 ; color: control.pressed ? "blue" : "grey"}
GradientStop { id : cdGradient; position: 1.0; color: control.pressed ? "blue" : "grey"}
GradientStop { position: 1 ; color: control.pressed ? "lightblue" : "#ccc"}
}
// 完成"冷却"过程
PropertyAnimation
{
target: cdGradient
property: "position"
from : 1.0
to : 0.0
duration: chillDownDuration
running: chillDown
// 启动时,置按钮无效
onStarted: {buttonSelf.enabled = false}
// 动画停止时,置按钮有效,冷却标志为无效
onStopped: {buttonSelf.enabled = true;chillDown=false}
}
}
}
}