Reputation: 139
Please can someone explain me one thing. Suppose I have an item, if I click it, then a drop-down menu appears. How to make that when you hover over menu items, they stand out like that?
Code:
Rectangle {
id: main_window
width: 600
height: 600
property int mrg: 10
Rectangle {
anchors.centerIn: parent
width: 500
height: 500
color: 'green'
Text {
id: field
text: "Click!"
font.pointSize: 20
color: 'white'
anchors.centerIn: parent
MouseArea {
id: ma
anchors.fill: parent
hoverEnabled: true
onClicked: {
menu.x = ma.mouseX
menu.open()
}
}
Menu {
id: menu
y: field.height
MenuItem {
text: "Menu item"
highlighted: true
}
}
}
}
}
In the documentation, I came across the point that the proper highlight
is responsible for selecting the appropriate menu item. I installed it in the True, but it did not change anything.
Please tell me what I'm doing wrong. Thanks a lot.
Upvotes: 2
Views: 2035
Reputation: 11072
The default implementation of MenuItem
doesn't include any visual highlighting feature, but you can adapt the graphical representation to your needs as explained in the Qt manuals. So, your MenuItem
should look like this:
MenuItem {
id: control
text: "Menu item"
background: Item {
implicitWidth: 200
implicitHeight: 40
Rectangle {
anchors.fill: parent
anchors.margins: 1
color: control.highlighted ? "blue" : "transparent" // blue background if the control is highlighed
MouseArea {
anchors.fill: parent
hoverEnabled: true // enable mouse enter events when no mouse buttons are pressed
onContainsMouseChanged: control.highlighted = containsMouse // set the highlighted flag when the mouse hovers the MenuItem
}
}
}
}
Note that this implementation is based on the default implementation provided by Qt:
background: Item { implicitWidth: 200 implicitHeight: 40 Rectangle { x: 1 y: 1 width: parent.width - 2 height: parent.height - 2 color: control.visualFocus || control.down ? Default.delegateColor : "transparent" } }
Note that Bob's answer simplifies this solution by eliminating the MouseArea
Upvotes: 2
Reputation: 415
Although it's an old question, I came across this as it was something I was wanting to do myself. I think m7913d's answer can be simplified a little by making use of the hovered
property of MenuItem
.
MenuItem {
id: control
text: "Menu item"
hoverEnabled: true
background: Item {
implicitWidth: 200
implicitHeight: 40
Rectangle {
anchors.fill: parent
anchors.margins: 1
color: control.hovered ? "blue" : "transparent"
}
}
}
The other thing I did was to retain the control.down
handling of the original implementation, so the color
expression is slightly more involved than shown here.
Upvotes: 3