德克士内 将Button 实现 ButtonGroup 的效果 三个Button 悬停变色 选中button 变化
其实我是想写Emit的,写着写着成了group 那就还是叫 EmitButton 明天上传优快云 我还在归程…… 节日快乐
先说几句废话,Button 作为一个独立的个体,我们可以将公开的属性提炼出来,所以有了 中的 property(属性),这样就可以当控件使用,这其实是Qt QML 组件的一种形式。
CButton.qml
import QtQuick 2.6
Rectangle {
color: "#00000000"
width: 200
height: 50
id:cButton
signal buttonClick(int index) // QML 信号的声明
property int buttonIndex: 0 //自身序号
property int currentButtonIndex: 0 //buttonGroup 序号
property string normalSource: "" //图片状态
property string hoverSource: "" //悬停状态
property alias buttonText: buttonContext.text //alias 别名 直接修改的是Text 的内容
property alias buttonSouce : buttonBackGroundImage.source
property bool isEnter:false
Image {
id: buttonBackGroundImage
anchors.fill: parent
source: cButton.buttonIndex===cButton.currentButtonIndex ? hoverSource : (isEnter===true ? hoverSource : normalSource)
//这个是一个小的方法,就是判断是不是选中 如果不是 判断是不是悬停
}
Text {
id: buttonContext
text: qsTr("text")
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
}
MouseArea {
id:mouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: {
buttonClick(cButton.buttonIndex) //发送 signal QML 中不用写 emit
}
onEntered: {
cButton.isEnter=true
}
onExited: {
cButton.isEnter=false
}
}
}
main.qml 就是Button 们的属性设置了 这里多了 一个方法的定义 和 信号与槽的连接
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{
anchors.fill: parent
id:buttonGroup
//初始化三个button
CButton{
id:leftButton
buttonIndex:0
currentButtonIndex :0
buttonText:qsTr("左")
anchors.left: parent.left //anchors 布局神器
anchors.top: parent.top
anchors.topMargin: 10
anchors.leftMargin: 10
normalSource:"qrc:/image/Button.png"
hoverSource:"qrc:/image/Button_hover.png"
}
CButton{
id:centerButton
buttonIndex:1
currentButtonIndex :0
buttonText:qsTr("中")
anchors.left: leftButton.right
anchors.top: leftButton.top
anchors.leftMargin: 10
normalSource:"qrc:/image/Button.png"
hoverSource:"qrc:/image/Button_hover.png"
}
CButton{
id:rightButton
buttonIndex:2
currentButtonIndex :0
buttonText:qsTr("右")
anchors.left: centerButton.right
anchors.top: centerButton.top
anchors.leftMargin: 10
normalSource:"qrc:/image/Button.png"
hoverSource:"qrc:/image/Button_hover.png"
}
}
//方法的定义 最开始我会把 currentButtonIndex 放到 main.qml 更符合流程,但是改变当前选中Button 就需要遍历Button们或者记录操作顺序
function buttonClick( index) // QML 中定义 函数(方法) 注意 参数不用加类型 js 写法
{
leftButton.currentButtonIndex= index
centerButton.currentButtonIndex= index
rightButton.currentButtonIndex= index
}
//如果有一天 ,没有信号与槽,我就告别QT编程了
Component.onCompleted: { // QML 信号 与 槽(函数)的连接方法 QtWidgets 会详细介绍这一核心机制
leftButton.buttonClick.connect(buttonClick)
centerButton.buttonClick.connect(buttonClick)
rightButton.buttonClick.connect(buttonClick)
}
}