QML按钮渐变及多种状态实现(附完整工程)
发布日期:2021-05-13 21:00:44 浏览次数:28 分类:精选文章

本文共 2373 字,大约阅读时间需要 7 分钟。

QButton按钮效果展示与实现

本文将详细介绍QML(Qt Quick)中自定义按钮控件QButton的实现效果及其实现方法

按钮渐变效果

QButton控件支持不同状态下的渐变背景效果,具体实现如下

Rectangle {
id: leave
gradient: Gradient {
GradientStop { position: 0.0; color: "#787878" }
GradientStop { position: 0.495; color: "#000000" }
GradientStop { position: 0.495; color: "#000000" }
GradientStop { position: 1.0; color: "#787878" }
}
}
Rectangle {
id: hover
gradient: Gradient {
GradientStop { position: 0.0; color: "#AAAAAA" }
GradientStop { position: 0.495; color: "#000000" }
GradientStop { position: 0.495; color: "#000000" }
GradientStop { position: 1.0; color: "#AAAAAA" }
}
}

按钮状态交互

通过MouseArea组件实现按钮的按压、悬停、释放等状态交互

MouseArea {
anchors.fill: parent
hoverEnabled: true
onPressed: {
parent.gradient = leave.gradient
root.pressed()
//文字下沉效果
buttonText1.x = buttonText1.x + 1
buttonText1.y = buttonText1.y + 1
}
onEntered: {
parent.gradient = hover.gradient
root.hovered()
}
onExited: {
parent.gradient = leave.gradient
}
onReleased: {
parent.gradient = hover.gradient
root.released()
//文字恢复效果
buttonText1.x = buttonText1.x - 1
buttonText1.y = buttonText1.y - 1
}
onClicked: {
root.clicked()
}
}

文字下沉效果实现

通过在按钮按压时移动文字位置,实现文字下沉的视觉效果

Text {
id: buttonText
text: "Button"
visible: false
anchors.centerIn: parent
color: "white"
font.pointSize: 15
}
Text {
id: buttonText1
text: buttonText.text
x: buttonText.x
y: buttonText.y
color: buttonText.color
font.pointSize: buttonText.font.pointSize
}

按钮在主.qml中的使用

主.qml中使用QButton控件的示例代码如下

import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 480
height: 240
title: qsTr("Hello QButton")
QButton {
id: btn1
x: 100
y: 100
textSize: 15
onClicked: console.log("---------被点击")
onPressed: console.log("---被按下")
onHovered: console.log("*****指针来了*****")
}
QButton {
anchors.left: btn1.right
anchors.top: btn1.top
anchors.leftMargin: 4
text: "胡皓天"
width: 140
height: 40
}
}

项目展示

通过以上实现,可在按钮按压时显示文字下沉效果,在释放时恢复原状,完美呈现按钮交互的视觉反馈

如果需要更详细的技术实现和优化,可以参考完整的QButton.qml和main.qml代码文件

上一篇:“上帝模式”伪装文件夹以及防止删除
下一篇:cmd获取当前文件夹下指定后缀文件名

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月11日 18时31分06秒