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