文章目录
-
-
- 演示
- 代码实现
- 实际调用
-
演示

- 图标文本可自定义
- 按下颜色可自定义
- 进入颜色可自定义
- 退出颜色可自定义
- 可自定义鼠标左键按下功能
- 可自定义鼠标右键按下功能
代码实现
MyIconButton.qml文件
import QtQuick 2.0
Rectangle {
id: rec
property alias img_src: icon.source
property alias btn_txt: button.text
property color clr_enter: "#dcdcdc"
property color clr_exit: "#ffffff"
property color clr_click: "#aba9b2"
property color clr_release: "#ffffff"
//自定义点击信号
signal clickedLeft()
signal clickedRight()
signal release()
width: 130
height: 130
radius: 10
Image {
id: icon
width: 80
height: 80
source: "qrc:/camera.png"
fillMode: Image.PreserveAspectFit
clip: true
anchors.top: parent.top
anchors.right: parent.right
anchors.left: parent.left
anchors.margins: 10
}
Text {
id: button
text: qsTr("button")
anchors.top: icon.bottom
anchors.topMargin: 5
anchors.horizontalCenter: icon.horizontalCenter
anchors.bottom: icon.bottom
anchors.bottomMargin: 5
font.bold: true
font.pointSize: 14
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
//接受左键和右键输入
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
//左键点击
if (mouse.button === Qt.LeftButton)
{
parent.clickedLeft()
// console.log(button.text + " Left button click")
}
else if(mouse.button === Qt.RightButton)
{
parent.clickedRight()
// console.log(button.text + " Right button click")
}
}
//按下
onPressed: {
color = clr_click
}
//释放
onReleased: {
color = clr_enter
parent.release()
console.log("Release")
}
//指针进入
onEntered: {
color = clr_enter
// console.log(button.text + " mouse entered")
}
//指针退出
onExited: {
color = clr_exit
// console.log(button.text + " mouse exited")
}
}
}
实际调用
mai.qml文件
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 800
height: 480
title: qsTr("Hello World")
Text {
id: info
text: qsTr("无按键点击")
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
anchors.margins: 20
font.bold: true
font.pixelSize: 20
}
function setInfoText(str)
{
info.text = str;
}
Row {
spacing: 20
anchors.centerIn: parent
MyIconButton {
id: btn_camera
img_src: "qrc:/camera.png";
btn_txt: "相机"
onClickedLeft: setInfoText(btn_txt + " Left Button click")
onClickedRight: setInfoText(btn_txt + " Right Button click")
}
MyIconButton {
id: btn_video
img_src: "qrc:/dianshiju-.png";
btn_txt: "视频"
onClickedLeft: setInfoText(btn_txt + " Left Button click")
onClickedRight: setInfoText(btn_txt + " Right Button click")
}
MyIconButton {
id: btn_audio
img_src: "qrc:/music.png";
btn_txt: "音乐"
onClickedLeft: setInfoText(btn_txt + " Left Button click")
onClickedRight: setInfoText(btn_txt + " Right Button click")
}
}
}