2
votes

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

1 Answers

4
votes

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.