0
votes

I have an item that consists of an image:

Item {

    /* other stuff */

    Image {
            id: img
            anchors.fill: parent
    
            source: mySource
            asynchronous: true
            fillMode: Image.PreserveAspectFit
        }
}

I want to overlay a (transparent) rectangle of the same size on the image when one hovers over it, so that I can do stuff like provide captions for the image etc.

How would one go about doing this?

  1. My first try below: (I used console statements to verify that hovering on an image itself works)
import QtQuick 2.6

Item {
    Image {
        id: img
        anchors.fill: parent

        source: mySource
        asynchronous: true
        fillMode: Image.PreserveAspectFit

        MouseArea {
            enabled: img.status == Image.Ready
            anchors.fill: parent
            
            hoverEnabled: true
            onEntered: {
                console.log("Entering: ")
                overlay
            }
            onExited: {
                console.log("Exiting: ")
            }
        }

        Rectangle {
            id : overlay
            anchors.fill: parent
            color: "transparent"

            Text {
                id: imgcaption
                text: "Caption"
                anchors.bottom: overlay.bottom; anchors.verticalCenter: overlay.verticalCenter
                font.pointSize : 14
            }
        }
    }
}

When I do this I get something like this at all times, regardless of if I'm hovering over the image or not. enter image description here

  1. I also tried to put the Rectangle inside the onEntered handler itself, but when I do this the image doesn't display at all, and neither do the console statements so I'm not sure if this is valid QML.

It should be fairly obvious that I'm new to QML and don't really know what I'm doing, so I'd appreciate it if someone could point me in the right direction.

1

1 Answers

3
votes

Try toggling the visibility based on the containsMouse property, like this:

Item {
    Image {
        id: img
        anchors.fill: parent

        source: mySource
        asynchronous: true
        fillMode: Image.PreserveAspectFit

        MouseArea {
            id: mouseArea
            enabled: img.status == Image.Ready
            anchors.fill: parent
            
            hoverEnabled: true
        }

        Item {
            id : overlay
            anchors.fill: parent

            visible: mouseArea.containsMouse

            Text {
                id: imgcaption
                text: "Caption"
                anchors.bottom: overlay.bottom; anchors.verticalCenter: overlay.verticalCenter
                font.pointSize : 14
            }
        }
    }
}