异常情况
Button {
id: control
text: qsTr("Button")
width: 100
height: 150
property color normalColor: "green"
property color hoverColor: "yellow"
property color pressColor: "red"
background: Rectangle {
id: buttonBg
color : normalColor
}
MouseArea{
anchors.fill: parent
hoverEnabled: true
onEntered: {
buttonBg.color = control.hoverColor
}
onPressed: {
buttonBg.color = control.pressColor
}
onExited: {
buttonBg.color = control.normalColor
}
}
}
如果这样写会报错。
ReferenceError: normalColor is not defined
因为里面 normalColor 是个变量,还没有初始化。
解决办法
一,将背景色改为固定值。
background: Rectangle {
id: buttonBg
color : "green"
}
二、写到初始化完成之后
也就是将背景初始化放到组件完成之后
Button {
id: control
text: qsTr("Button")
width: 100
height: 150
property color normalColor: "green"
property color hoverColor: "yellow"
property color pressColor: "red"
background: Rectangle {
id: buttonBg
}
MouseArea{
anchors.fill: parent
hoverEnabled: true
onEntered: {
buttonBg.color = control.hoverColor
}
onPressed: {
buttonBg.color = control.pressColor
}
onExited: {
buttonBg.color = control.normalColor
}
}
Component.onCompleted: {
buttonBg.color = normalColor;
console.log("Component.onCompleted")
}
}