我有一个由图像组成的项目:
Item {
/* other stuff */
Image {
id: img
anchors.fill: parent
source: mySource
asynchronous: true
fillMode: Image.PreserveAspectFit
}
}
当将鼠标悬停在图像上时,我想在图像上覆盖一个相同大小的(透明)矩形,以便我可以执行诸如为图像提供标题等操作。
如何去做这件事?
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
}
}
}
}
当我这样做时,无论我是否将鼠标悬停在图像上,我总是会得到类似的信息。
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可能会更好。它天生就是为了处理悬停事件,所以你不必设置
hoverEnabled
或 anchors
。
更重要的是,它对于鼠标移动是透明的。这在更棘手的场景中非常有用,例如处理已经包含交互式控件(Button、Flickable、MouseArea 等)的项目的悬停事件。
如果在这种情况下您仍然使用 MouseArea,它可能会中断这些控件处理悬停事件的方式,而 HoverHandler 则不会。 (MouseArea 有一个
propagateComposedEvents
属性,它仅控制是否传播 clicked、doubleClicked 和 pressAndHold。)
如果您仍然想使用 MouseArea,我找到了这种更新的方法:
MouseArea{
anchors.fill:parent
hoverEnabled:true
onHoveredChanged: {
if(containsMouse){
pannel.state ="hovered"
}else if(pannel.clicked){
pannel.state = "selection"
}else{
pannel.state = "unHovered"
}
}
}
我在 onEntered:{} 方面遇到了一些问题,也许它在最近的 qt 版本中被删除了?