Search code examples
qtqmlqtquick2qtquickcontrols2

QML MenuItem Highlighted doesn't work


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.


Solution

  • 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