繁体   English   中英

在 QML 中鼠标悬停时加载矩形

[英]Loading a Rectangle upon mouse hover in QML

我有一个包含图像的项目:

Item {

    /* other stuff */

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

当一个人将鼠标悬停在图像上时,我想在图像上覆盖一个相同大小的(透明)矩形,这样我就可以做一些事情,比如为图像提供标题等。

怎么做呢?

  1. 我的第一次尝试如下:(我使用控制台语句来验证悬停在图像本身是否有效)
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
            }
        }
    }
}

当我这样做时,无论我是否将鼠标悬停在图像上,我都会得到类似的东西。 在此处输入图像描述

  1. 我还尝试将 Rectangle 放在onEntered处理程序本身中,但是当我这样做时,图像根本不显示,控制台语句也不显示,所以我不确定这是否是有效的 QML。

很明显,我是 QML 的新手,并不真正知道自己在做什么,所以如果有人能指出我正确的方向,我将不胜感激。

尝试根据containsMouse属性切换可见性,如下所示:

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
            }
        }
    }
}

HoverHandler可能会更好。 它是为处理悬停事件而生的,因此您不必设置hoverEnabledanchors

更重要的是,它对鼠标移动是透明的。 这在更棘手的场景中会很有用,例如处理已经包含交互式控件(Button、Flickable、MouseArea 等)的项目的悬停事件。

如果在这种情况下仍然使用 MouseArea,它可能会中断这些控件处理悬停事件的方式,而 HoverHandler 不会。 (MouseArea 有一个propagateComposedEvents属性,它只控制clickeddoubleClickedpressAndHold是否被传播。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM