Below is my Qml code:
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"
}
}
I want to access this button's style property, change the background.color when mouse is hover. But the console.log outpu is always
qrc:/qmls/menu.qml:40: ReferenceError: tt1 is not defined
How to get the element using JavaScript? Or do we have other approach to change background color when mouse is entered.
Answering to your question, you should define public property like:
Button {
id: root
property color backgroundColor: pressed ? 'skyblue'
: mousearea.entered ? "lightsteelblue"
: "#2e2e2e"
...
MouseArea { id: mousearea; ... }
style: ButtonStyle {
background: Rectanlge { color: root.backgroundColor; ... }
}
}
and then use is property to override default implementation.
But,
You are trying to use styles in a completely wrong way. Style
is a visual representation of Control
's state and should't be changed manually in run-time. So, a proper way is to bind control properties to style (e.g. using property control
).
style: ButtonStyle {
background: Rectangle {
color: control.hovered ? 'lightsteelblue'
: 'skyblue'
}
}
You can achieve something similar without using styles by nesting a rectangle inside the button and then using the onHoveredChanged property to modify the opacity. An example is below. I did it this way to avoid conflicting with the normal button style's hover effect.
Button {
text: "Push me"
Rectangle{
id: myRectId
anchors.fill: parent
anchors.margins: 1
color: "green"
opacity : .2
}
onHoveredChanged: hovered ? myRectId.opacity = 0 : myRectId.opacity = .2;
}
This ends up looking like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With