以下是我的Qml代码:
Button {
id: newMenu
anchors {
top: topMenu.top
topMargin: 15
left: topMenu.left
leftMargin: 16
}
text: "New"
iconSource: "../images/New.png"
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true //this line will enable mouseArea.containsMouse
onClicked: {
newProjectFileDlg.visible = true
}
onEntered: {
console.log(tt1);
}
}
style: ButtonStyle {
id: buttonStyle
background: Rectangle {
id: tt1
implicitWidth: 100
implicitHeight: 25
border.width: 0
radius: 4
color: mousearea.entered ? "lightsteelblue" : "#2e2e2e"
}
}
Run Code Online (Sandbox Code Playgroud)
我想访问此按钮的样式属性,当鼠标悬停时更改background.color.但是console.log outpu总是如此
qrc:/qmls/menu.qml:40: ReferenceError: tt1 is not defined
Run Code Online (Sandbox Code Playgroud)
如何使用JavaScript获取元素?或者我们还有其他方法可以在输入鼠标时更改背景颜色.
回答你的问题,你应该定义公共财产,例如:
Button {
id: root
property color backgroundColor: pressed ? 'skyblue'
: mousearea.entered ? "lightsteelblue"
: "#2e2e2e"
...
MouseArea { id: mousearea; ... }
style: ButtonStyle {
background: Rectanlge { color: root.backgroundColor; ... }
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用 is 属性来覆盖默认实现。
但,
您试图以完全错误的方式使用样式。Style是 的状态的直观表示Control,不应在运行时手动更改。因此,正确的方法是将控件属性绑定到样式(例如使用 property control)。
style: ButtonStyle {
background: Rectangle {
color: control.hovered ? 'lightsteelblue'
: 'skyblue'
}
}
Run Code Online (Sandbox Code Playgroud)