【问题标题】:How to highlight image on mouse hoover QML如何在鼠标悬停 QML 上突出显示图像
【发布时间】:2021-09-13 10:51:02
【问题描述】:

我是 QML 的新手,我正在尝试突出显示鼠标悬停上的图像。我有一排电影图像,像这样:

这是我的图像编号 4 (tarzan) 的代码:

Rectangle{
   id:rect4
   width: parent.width/5-row.spacing/5
   height:parent.height
   color:'transparent'
   Image{
       id: tarzan
       fillMode: Image.PreserveAspectFit
       anchors.fill: parent
       source:'qrc:tarzan.jpg'
       MouseArea{
           id:area
           width:parent.width
           height: parent.height
           hoverEnabled: true
           anchors.fill:parent
           onClicked:tarzan.forceActiveFocus()
       }

我尝试了不同的方法,但没有任何反应。有任何想法吗?帮助将不胜感激。

【问题讨论】:

  • 我没有看到任何处理悬停状态的代码。也许看看 containsMouse 属性和 MouseArea 的 enteredexited 信号
  • 好的,但是为什么onClicked 不起作用?
  • onClicked 对活动的鼠标点击做出反应,它对我有用。 Image 的 .forceActiveFocus() 方法不会突出显示图像,因此您必须实现另一种突出显示该图像的方法
  • 我试过onClicked: console.log("Button clicked!"),也没有任何反应。
  • 感谢您的回答。我使用输入和退出信号解决了它。在里面我使用了tarzan.scale=1.2,它起作用了。当我用鼠标悬停在图像上时,图像会改变大小。

标签: image qt qml mousearea


【解决方案1】:

如果您使用的是 qt quick 2.15 版,有两种方法可以做到这一点

import QtQuick 2.15

你可以像这样使用 HoverHandler 对象

Image{
       id: tarzan
       fillMode: Image.PreserveAspectFit
       anchors.fill: parent
       source:'qrc:tarzan.jpg'
       HoverHandler{
          onHoveredChanged: {
              if(hovered){
                  tarzan.scale = 1.2
              }
              else{
                  tarzan.scale = 1
              }
          }

      }

如果你使用 qtquick 低于 2.15 的任何东西,那么你的 mousearea 对象应该看起来像这样

那就是鼠标区号这样的东西

MouseArea{
           id:area
           width:parent.width
           height: parent.height
           hoverEnabled: true
           anchors.fill:parent
           onContainsMouseChanged: {
              if(containsMouse){
                  tarzan.scale = 1.2
              }
              else{
                  tarzan.scale = 1
              }
          }
           onClicked:tarzan.forceActiveFocus()
       }

【讨论】:

  • 为什么不在scale: area.containsMouse ? 1.2 : 0 之前id: tarzan
  • 是的,我们也可以这样做,但是,我使用 if else 来保持简单,并使用相同的对象回答问题,如果我们将图像的比例设为零,图像会从此消失。如果您只是想要缩放效果,则不建议将比例设为零
  • 在 QML 中,绑定比 if-else 更受青睐,因为它具有某些优点,例如:代码更具可读性,由于语言优化了此类操作,因此节省了资源等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 2011-09-23
相关资源
最近更新 更多