detect when mouse cursor is over an irregular shape picture in Qt5 and QML

社会主义新天地 提交于 2020-01-15 06:18:09

问题


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

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/30142751/detect-when-mouse-cursor-is-over-an-irregular-shape-picture-in-qt5-and-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!