qtqml

button hover state in mousarea


I want to use a Button within a MouseArea, and when the mouse moves over the button, I want both to be in a hovered state. However, when I move over the button, the MouseArea exits the hovered state because the MouseArea's signal for 'exited' is executed when the mouse moves over the button.

I want something like the image below:

Expected output

Code:

Window {
    visible: true
    minimumWidth: 600
    minimumHeight: 320

    Rectangle
    {
        id: idRec1
        width: 200
        height: 200
        color: itemHovered ? Qt.lighter("red", 1.5) :"red"
        anchors.centerIn: parent

        property bool itemHovered: false

        MouseArea
        {
            anchors.fill: parent
            propagateComposedEvents: true
            hoverEnabled:true

            onEntered: idRec1.itemHovered = true
            onExited: idRec1.itemHovered = false
        }

        Button
        {
            anchors.centerIn: parent
            text: "Button"
        }
    }
}

Solution

  • You can solve your problem by moving your Button inside your MouseArea, i.e.

    Recatangle {
        MouseArea {
            Button { }
        }
    }
    

    Or as iam_peter suggested, use HoverHandler:

    Rectangle {
        HoverHandler { }
        Button { }
    }
    

    However, instead of MouseArea, I recommend using Frame or Pane, because both offer:

    These properties provide a visual cue for users when the mouse hovers over or enters the Frame/Pane, they adjust their geometry based on their children, and they maintain the hovered state even when the mouse moves over child elements within the Frame/Pane.

    Pane {
        id: view
        implicitWidth: 350
        hoverEnabled: true
        property int indent: 40
        property string text: "New View1"
        background: Rectangle { color: Qt.darker("#444", view.hovered ?  1.8 : 1) }
        RowLayout {
            width: parent.width
            IconButton { Layout.leftMargin: view.indent; icon.source: "address-book.svg" }
            Label { Layout.fillWidth:true; text: view.text }
            RowLayout {
                visible: view.hovered
                IconButton { icon.source: "reset.svg"; ToolTip.text: "Click to start the instance" }
                IconButton { icon.source: "pencil-square.svg"; ToolTip.text: "Modify View Name" }
                IconButton { icon.source: "x.svg"; ToolTip.text: "Delete View" }
            }
        }
    }
    

    You can Try it Online!

    FrameHover.gif