QML Button 背景为白色 点击时蓝色 实例
时间: 2024-03-02 20:53:38 浏览: 20
可以使用QML中的MouseArea和PropertyChanges组件来实现这个效果。具体实现方法如下:
1. 创建一个Button,并将其背景设置为白色:
```qml
Button {
id: myButton
text: "Click me"
background: Rectangle {
color: "white"
}
}
```
2. 在Button内部添加一个MouseArea组件,并设置其acceptedButtons属性为Qt.LeftButton,这样只有在鼠标左键点击时才会触发点击事件:
```qml
Button {
id: myButton
text: "Click me"
background: Rectangle {
color: "white"
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton
onClicked: {
// 添加代码
}
}
}
```
3. 在MouseArea的onClicked信号槽中,使用PropertyChanges组件来改变Button的背景颜色:
```qml
Button {
id: myButton
text: "Click me"
background: Rectangle {
color: "white"
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton
onClicked: {
PropertyChanges.target(myButton.background).color = "blue"
}
}
}
```
这样,当鼠标左键点击Button时,Button的背景颜色就会变为蓝色。