Sur cette page

Carte minimale (QML)

Le code minimal pour afficher une carte à l'aide de Qt Quick.

Fenêtre de l'application affichant une carte du centre d'Oslo

L'exemple «Carte minimale » montre comment utiliser l'élément Map pour afficher une carte. Il présente le code minimal nécessaire à l'affichage de la carte et peut servir de base à d'autres expérimentations.

Exécution de l'exemple

Vous pouvez exécuter l'exemple à partir de :

Code C++

Dans main.cpp, nous utilisons uniquement les classes QGuiApplication et QQmlApplicationEngine.

#include <QGuiApplication>
#include <QQmlApplicationEngine>

Dans la fonction main, nous instancions d’abord un objet QGuiApplication. Ensuite, nous créons un QQmlApplicationEngine et lui demandons de charger main.qml à partir du système de ressources Qt.

Enfin, QGuiApplication::exec() lance la boucle d’événements principale.

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Code QML

Dans ` main.qml`, nous importons le module QML ` QtLocation ` et le module QML ` QtPositioning ` dont il dépend. Ensuite, nous créons la fenêtre de niveau supérieur, lui attribuons une taille par défaut raisonnable et la rendons visible. La fenêtre sera occupée par un élément ` Map ` affichant la carte.

import QtQuick
import QtLocation
import QtPositioning

Window {
    width: Qt.platform.os == "android" ? Screen.width : 512
    height: Qt.platform.os == "android" ? Screen.height : 512
    visible: true
    title: map.center + " zoom " + map.zoomLevel.toFixed(3)
           + " min " + map.minimumZoomLevel + " max " + map.maximumZoomLevel

    Plugin {
        id: mapPlugin
        name: "osm"
    }

    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(59.91, 10.75) // Oslo
        zoomLevel: 14
        property geoCoordinate startCentroid

        PinchHandler {
            id: pinch
            target: null
            onActiveChanged: if (active) {
                map.startCentroid = map.toCoordinate(pinch.centroid.position, false)
            }
            onScaleChanged: (delta) => {
                map.zoomLevel += Math.log2(delta)
                map.alignCoordinateToPoint(map.startCentroid, pinch.centroid.position)
            }
            onRotationChanged: (delta) => {
                map.bearing -= delta
                map.alignCoordinateToPoint(map.startCentroid, pinch.centroid.position)
            }
            grabPermissions: PointerHandler.TakeOverForbidden
        }
        WheelHandler {
            id: wheel
            // workaround for QTBUG-87646 / QTBUG-112394 / QTBUG-112432:
            // Magic Mouse pretends to be a trackpad but doesn't work with PinchHandler
            // and we don't yet distinguish mice and trackpads on Wayland either
            acceptedDevices: Qt.platform.pluginName === "cocoa" || Qt.platform.pluginName === "wayland"
                             ? PointerDevice.Mouse | PointerDevice.TouchPad
                             : PointerDevice.Mouse
            rotationScale: 1/120
            property: "zoomLevel"
        }
        DragHandler {
            id: drag
            target: null
            onTranslationChanged: (delta) => map.pan(-delta.x, -delta.y)
        }
        Shortcut {
            enabled: map.zoomLevel < map.maximumZoomLevel
            sequence: StandardKey.ZoomIn
            onActivated: map.zoomLevel = Math.round(map.zoomLevel + 1)
        }
        Shortcut {
            enabled: map.zoomLevel > map.minimumZoomLevel
            sequence: StandardKey.ZoomOut
            onActivated: map.zoomLevel = Math.round(map.zoomLevel - 1)
        }
    }
}

L’élément Plugin est nécessaire pour définir le fournisseur de carte que nous allons utiliser. L’exemple peut fonctionner avec n’importe quel plugin de services géographiques disponible. Cependant, certains plugins peuvent nécessiter des paramètres supplémentaires pour fonctionner correctement, et nous pouvons utiliser PluginParameter pour les spécifier. Dans cet exemple, nous utilisons le plugin osm, qui est un plugin OpenStreetMap de typeQt Location et ne nécessite aucun paramètre.

Dans l’élément « Map », nous indiquons l’ plugin que nous utilisons et nous définissons l’ center et l’ zoomLevel de la carte.

Prérequis

Cet exemple nécessite une connexion Internet opérationnelle pour télécharger les tuiles cartographiques d’ OpenStreetMap. Un proxy système facultatif devrait être détecté automatiquement.

Exemple de projet sur code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.