检测鼠标光标何时在 Qt5 和 QML 中的不规则形状图片上 [英] detect when mouse cursor is over an irregular shape picture in Qt5 and QML

查看:35
本文介绍了检测鼠标光标何时在 Qt5 和 QML 中的不规则形状图片上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Qt5 和 QML(QtCreator 和 C++)开发一个小应用程序.

I'm developing a little application with Qt5 and QML (QtCreator and C++).

我想显示带有国家/地区的地图,当用户将鼠标移到一个国家/地区时,我想更改该国家/地区的颜色,认为这很容易,如果所有国家/地区都是矩形.

I would like to display a map with countries and when user passes the mouse over a country I would like to change the color of the country, thought it would be easy, and it is if all countries were rectangles.

    Image {
    id: mycountry
    width: 250
    height: 250
    source: "images/myCountry_gray.png"

    MouseArea {
        anchors.fill: parent
        hoverEnabled : true
        onEntered: {
            region.source = "images/myCountry_red.png"
        }
        onExited: {
            region.source = "images/myCountry_gray.png"
        }
    }
}

不幸的是,国家有不规则的形状,我只想在鼠标光标在其边界内时突出显示该国家

Unfortunately, countries have irregular shapes, and I would like only highlight the country when mouse cursor is inside its frontier

你知道如何开发它吗?我认为单独使用 QML 是不可能的.

Have you some idea how to develop that? I think it won't be possible using QML alone.

推荐答案

使用 QPainterPath 构建每个国家的形状.您可以使用 moveTo()lineTo().一旦你有了这个,让它成为自定义 QQuickItem 的成员变量 - 让我们调用它 CountryItem.在通过 CountryMapModule 将图像暴露给 QML 后,您可以使图像成为该项目的子项:

Use QPainterPath to construct the shape of each country. You can do this using moveTo() and lineTo(). Once you have this, make it a member variable of a custom QQuickItem - let's call it CountryItem. You could make the image a child of this item after exposing it to QML via CountryMapModule:

import CountryMapModule 1.0

CountryItem {
    implicitWidth: mapImage.implicitWidth
    implicitHeight: mapImage.implicitHeight

    Image {
        id: mapImage
        source: ":/images/australia.png"
    }
}

覆盖 QQuickItem::mouseMoveEvent() 以允许项目检查鼠标移动.QPainterPathcontains() 函数可以然后用于检查鼠标是否在其中.您可能需要缩放路径以适合图像的大小.

Override QQuickItem::mouseMoveEvent() to allow the item to check for mouse movement. The contains() function of QPainterPath can then be used to check if the mouse is inside it. You may need to scale the path to fit the size of the image.

这篇关于检测鼠标光标何时在 Qt5 和 QML 中的不规则形状图片上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆