【1】自定义一个按钮
import QtQuick 2.12
import QtQuick.Templates 2.12 as Template
import QtQuick.Controls 2.12
import QtQuick.Controls.impl 2.12
Template.Button {
id: control
property color textColor: "white"
property string source: ""
property string source2: ""
property color backgroundTheme: "#1a2933"
property color backgroundColor: control.down ? Qt.darker(
backgroundTheme) : (control.hovered
|| control.highlighted) ? Qt.lighter(backgroundTheme) : control.checked ? backgroundTheme : backgroundTheme
property int radius: 10 //背景rect的圆角
property int borderWidth: 0
implicitWidth: 55
implicitHeight: 55
leftPadding: 0
rightPadding: 5
spacing: 10
font {
family: "SimSun"
pixelSize: 30
}
contentItem: Row {
id: btn_row
width: control.width
spacing: control.spacing
Image {
id: btn_icon
anchors {
verticalCenter: parent.verticalCenter
}
}
Text {
id: btn_text
anchors {
verticalCenter: parent.verticalCenter
}
width: btn_icon.width ? btn_row.width - btn_row.spacing - btn_icon.width : btn_row.width
text: control.text
color: control.textColor
renderType: Text.NativeRendering
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
elide: Text.ElideRight
font: control.font
}
}
IconImage {
id: icon
x: 0
y: 0
width: control.width
height: control.height
source: control.source
}
//背景
background: Rectangle {
implicitWidth: control.implicitWidth - 10
implicitHeight: control.implicitHeight - 10
radius: control.radius
//visible: !control.flat || control.down || control.checked || control.highlighted
color: control.backgroundColor
border.width: borderWidth
border.color: "red"
}
}
【2】特效1:闪烁
CNCButton {
id: ledButton
onClicked: {
}
}
function Render() {
var date = new Date()
var seconds = date.getUTCSeconds()
if (seconds % 2 === 0) {
ledButton.source = "qrc:/images/ledRed.png"
} else {
ledButton.source = "qrc:/images/ledGreen.png"
}
}
【3】特效2:鼠标在上方变色,鼠标移开恢复:重写onHoveredChanged事件
onHoveredChanged: {
if (source === pic2) {
source = pic1
} else {
source = pic2
}
}