(→Issues) |
|||
| Line 99: | Line 99: | ||
QDeclarativeView view; | QDeclarativeView view; | ||
view.setSource(QUrl::fromLocalFile("map.qml")); | view.setSource(QUrl::fromLocalFile("map.qml")); | ||
| + | view.setResizeMode(QDeclarativeView::SizeRootObjectToView); | ||
view.show(); | view.show(); | ||
Contents |
This page is inspired by the discussion at [1].
It is meant to provide a basis for real life applications. This means that it is limited to qt and qtmobility versions available to the end user of maemo5, symbian and meego. As the time of this writing this especially limits qtmobility to version 1.1 as version 1.2 is not available for symbian.
Wouldn't it be nice to be able to add a map to a qml program just like this?
// map.qml
import QtQuick 1.0
import MyWidgets 1.0
Rectangle {
id: page
width: 800; height: 480
Map {
anchors.fill: parent
}
}
It is! The following custom map widget provides basic scrolling/panning capabilities and implements the necessary parameter less constructor:
// map_widget.cpp
#include <QGeoServiceProvider>
#include <QGeoMappingManager>
#include <QGraphicsSceneMouseEvent>
#include <QGeoCoordinate>
#include "map_widget.h"
// A widget for QML, therefore we need the parameter-less constructor.
MapWidget::MapWidget() :
QGraphicsGeoMap((new QGeoServiceProvider("nokia"))->mappingManager())
{
setCenter(QGeoCoordinate(51.05, 13.73));
setZoomLevel(17);
}
// without this no mouseMoveEvent()'s are reported
void MapWidget::mousePressEvent(QGraphicsSceneMouseEvent*) { }
void MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
QPointF dp(event->lastPos() - event->pos());
pan(dp.x(), dp.y());
}
The matching header file is also pretty simple:
// map_widget.h
#ifndef MAP_WIDGET_H
#define MAP_WIDGET_H
#include <QGraphicsGeoMap>
#include <QGraphicsGeoMap>
QTM_USE_NAMESPACE
class MapWidget : public QGraphicsGeoMap
{
Q_OBJECT
public:
MapWidget();
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event);
void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
};
#endif // MAP_WIDGET_H
This map widget has to be made available to the qml interpreter. Thus the following simple program makes the map widget avaiable to qml and runs the map.qml example:
#include <QApplication>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeView>
#include "map_widget.h"
int main(int argc, char ** argv)
{
QApplication app(argc, argv);
qmlRegisterType<MapWidget>("MyWidgets", 1, 0, "Map");
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("map.qml"));
view.setResizeMode(QDeclarativeView::SizeRootObjectToView);
view.show();
return app.exec();
}
Finally a simple .pro file is needed for qmake:
TEMPLATE = app QT += declarative CONFIG += mobility MOBILITY = location # Input HEADERS += map_widget.h SOURCES += main.cpp map_widget.cpp
So far this code has been tested under Ubuntu 11.04 using the qt packages from the forum nokia ppa.
There is currently one problem with this code: