代码:
NavigationBarButton.qml
import QtQuick 2.2
import Qt5Compat.GraphicalEffects
Item
{
id:root
width: 130
height: 50
property bool onFarLeft :false
property bool onFarRight :false
property alias rectRadius:rect.radius
property alias barText:centerBarText.text
property alias barImage:img.source
signal barBtnclicked
Image
{
id:img
visible: false
x:(root.width - img.width)/2
y:0
z:1
states:
[
State
{
name: "enteredState"
PropertyChanges { target: img; visible: "true"}
PropertyChanges { target: img; y: 50}
PropertyChanges { target: img; z: 3}
}
]
transitions:
[
Transition
{
from: "*"; to: "enteredState"
SequentialAnimation
{
NumberAnimation{properties: "visible";duration: 50;}
NumberAnimation{properties: "y";duration: 500;}
}
},
Transition
{
from: "enteredState"; to: "*"
SequentialAnimation
{
NumberAnimation{properties: "y";duration: 500;}
NumberAnimation{properties: "visible";duration: 50;}
}
}
]
}
Item
{
anchors.fill: parent
clip: true
z:2
Rectangle
{
id:rect
anchors.fill: parent
anchors.rightMargin: onFarLeft ? -radius : 0
anchors.leftMargin: onFarRight? -radius : 0
opacity: 0.5
gradient:btnGradient
Gradient
{
id:btnGradient
GradientStop { position: 0.0; color: "#D1D1D1" }
GradientStop { position: 0.5; color: "#B6B6B6" }
GradientStop { position: 1.0; color: "#979797" }
}
Text
{
id:centerBarText
font.pointSize: 12
font.bold: true
color:"#333333"
anchors.horizontalCenter:parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.verticalCenterOffset: 0
}
DropShadow //文本阴影
{
anchors.fill: centerBarText
source: centerBarText
verticalOffset: 2
color: "#80000000"
radius: 1
}
MouseArea
{
id:rectMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onEntered:
{
rect.color = "#7E7E7E"
rect.gradient = undefined
centerBarText.color = "#FFFFFF"
img.state = "enteredState"
}
onExited:
{
rect.gradient = btnGradient
centerBarText.color = "#333333"
img.state = ""
}
onPressed:
{
centerBarText.anchors.verticalCenterOffset = 5
}
onReleased:
{
if(rectMouse.containsMouse)//鼠标在按钮范围才有效
root.barBtnclicked()
centerBarText.anchors.verticalCenterOffset = 0
}
}
}
}
}
main.qml
import QtQuick 2.14
import QtQuick.Window 2.14
Window
{
id:root
visible: true
width: 1200
height: 480
title: qsTr("Hello World")
Row
{
spacing: 1
anchors.top: parent.top
anchors.horizontalCenter:parent.horizontalCenter
NavigationBarButton{ barText:"Players";rectRadius: 10;onFarLeft: true;barImage: "qrc:/img/ipod.png"}
NavigationBarButton{ barText:"Camersa";barImage: "qrc:/img/video_camera.png"}
NavigationBarButton{ barText:"TVs";barImage: "qrc:/img/television.png"}
NavigationBarButton{ barText:"Screens";barImage: "qrc:/img/monitor.png"}
NavigationBarButton{ barText:"Tools";barImage: "qrc:/img/toolbox.png"}
NavigationBarButton{ barText:"Phones";barImage: "qrc:/img/telephone.png"}
NavigationBarButton{ barText:"Printers";rectRadius: 10;onFarRight: true;barImage: "qrc:/img/print.png"}
}
}
效果:
注意:为了图片不受clip属性的影响所以最外层是Item,第二层放置图片和设置clip为true的Item。
参考资料: