1. 说明
一般情况下,QML提供的按钮控件的外观效果比较单一,如果想要做出带有空间感的效果,需要自己定义组件实现。本篇博客记录两种效果的空间感按钮,主要借助阴影达到想要的效果。
效果展示:
2. 主要代码:
第一种:
import QtQuick 2.0
import QtGraphicalEffects 1.0
//自定义阴影按钮,阴影不可跳动
Item {
id : shadowButton
width: 100
height: 50
signal clicked();
Rectangle {
id : bgrect;
y : 20
x : 1
color: Qt.rgba(0.9,0.9,0.9,1)
width: shadowButton.width-2;
height: shadowButton.height-25
radius: height/2
}
DropShadow {
id : shadow
anchors.fill: bgrect
horizontalOffset: 2
verticalOffset: 12
radius: 8.0
samples: 17
color: Qt.rgba(0.3,0.3,0.3,0.7)
source: bgrect
}
Rectangle{
id : toprect
color: Qt.rgba(0.9,0.9,0.9,1)
width: shadowButton.width;
height: shadowButton.height-2
radius: height/3
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled : true
onClicked: {
animation.start();
shadowButton.clicked();
}
onEntered: {
toprect.color = Qt.rgba(0.7,0.7,0.7,1)
bgrect.color = Qt.rgba(0.95,0.95,0.95,1)
shadowText.color = "white"
}
onExited: {
toprect.color = Qt.rgba(0.9,0.9,0.9,1)
bgrect.color = Qt.rgba(0.9,0.9,0.9,1)
shadowText.color = Qt.rgba(0.3,0.3,0.3,1)
}
}
}
Text {
id: shadowText
anchors.centerIn: toprect
text: qsTr("click")
color: Qt.rgba(0.3,0.3,0.3,1)
font.pixelSize : toprect.height/2
}
SequentialAnimation {
id : animation
NumberAnimation {
target: toprect;
property: "y";
to: toprect.x+2;
duration: 50
}
NumberAnimation {
target: toprect;
property: "y";
to: toprect.x-2;
duration: 50
}
}
}
第二种:
import QtQuick 2.0
import QtGraphicalEffects 1.0
//自定义阴影按钮,阴影可跳动
Item {
id : shadowButton
width: 100
height: 50
signal clicked();
Rectangle{
id : toprect
color: Qt.rgba(0.9,0.9,0.9,1)
width: shadowButton.width;
height: shadowButton.height-2
radius: height/4
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled : true
onClicked: {
animation.start();
shadowButton.clicked();
}
onEntered: {
toprect.color = Qt.rgba(0.7,0.7,0.7,1)
shadowText.color = "white"
}
onExited: {
toprect.color = Qt.rgba(0.9,0.9,0.9,1)
shadowText.color = Qt.rgba(0.3,0.3,0.3,1)
}
}
}
DropShadow {
id : shadow
anchors.fill: toprect
horizontalOffset: 1
verticalOffset: 10
radius: 8.0
samples: 17
color: Qt.rgba(0.3,0.3,0.3,0.7)
source: toprect
}
Text {
id: shadowText
anchors.centerIn: toprect
text: qsTr("click")
color: Qt.rgba(0.3,0.3,0.3,1)
font.pixelSize : toprect.height/2
}
SequentialAnimation {
id : animation
ParallelAnimation {
NumberAnimation {
target: toprect;
property: "y";
to: toprect.x+2;
duration: 50
}
NumberAnimation {
target: shadow
property: "scale"
to:0.95
duration: 50
}
}
ParallelAnimation {
NumberAnimation {
target: toprect;
property: "y";
to: toprect.x-2;
duration: 50
}
NumberAnimation {
target: shadow
property: "scale"
to:1.0
duration: 50
}
}
}
}