1. 说明:
此自定义按钮的大致效果为:当点击了按钮控件后,会在按钮中心生成一个类似波纹的特效并向四周扩散,同时按钮控件会有一个跳动的特效。
效果展示
波纹按钮
2. 示例代码:
功能实现方式:在WaveButton.qml中使用动态创建组件的方式,创建WaveEffect.qml自定义控件,有关波纹的代码均在WaveEffect.qml中进行设计。相关代码如下:
WaveButton.qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
id:root
anchors.centerIn: parent
width: 100
height: 50
radius: height/4
color: Qt.rgba(0.9,0.9,0.9,1)
signal clicked()
function createWaveEffect()
{
var waveCom = Qt.createComponent("qrc:/WaveEffect.qml")
if(waveCom.status === Component.Ready)
{
var waveObj = waveCom.createObject(root,
{"waveDiameter":root.width > root.height ? root.height : root.width,
"waveBorderWidth":2,
"waveBorderColor" : Qt.rgba(0.95,0.95,0.95,1)
})
waveObj.anim.start()
}
}
MouseArea {
anchors.fill: parent
onClicked: {
createWaveEffect()
scaleAnim.start()
root.clicked()
}
}
Text {
id: waveText
anchors.centerIn: parent
text: qsTr("click")
color: Qt.rgba(0.3,0.3,0.3,1)
font.pixelSize : parent.width > parent.height ? parent.height * 0.4 : parent.width * 0.4
}
SequentialAnimation {
id: scaleAnim
running: false
loops: 1
NumberAnimation {
target: root
property: "scale"
to:0.95
duration: 100
}
NumberAnimation {
target: root
property: "scale"
to:1.0
duration: 100
}
}
}
WaveEffect.qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Item {
id:root
width: 200
height: 200
anchors.centerIn: parent
property alias anim : anim
property int waveDiameter : 0
property int waveBorderWidth : 1
property color waveBorderColor : Qt.rgba(0.8,0.8,0.8,1)
Rectangle {
id:wave
anchors.centerIn: parent
width:0
height: width
radius: height / 2
border.width: waveBorderWidth
border.color: waveBorderColor
color: Qt.rgba(0,0,0,0)
property alias anim : anim
property int duration : 800
onOpacityChanged: {
if(opacity === 0) {
root.destroy()
}
}
ParallelAnimation {
id:anim
running: false
loops: 1
NumberAnimation {
target: wave
properties: "width,height"
to:waveDiameter
duration: duration
}
NumberAnimation {
target: wave
properties: "radius"
to:waveDiameter
duration: duration
}
NumberAnimation {
target: wave
property: "opacity"
to: 0
duration: duration
}
}
}
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
WaveButton{
anchors.centerIn: parent
onClicked: {
console.log("create waveEffect Button ....")
}
}
}