20 #include <QApplication>
24 #include <QGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
28 #include <QMouseEvent>
30 #include <QPaintEvent>
33 #include <QTextStream>
34 #include <QResizeEvent>
36 #include <QStringList>
37 #include <QWheelEvent>
82 : QGraphicsView( parent )
86 , mAntiAliasing( false )
88 setObjectName( name );
89 mScene =
new QGraphicsScene();
91 setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
92 setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
109 setMouseTracking(
true );
110 setFocusPolicy( Qt::StrongFocus );
128 this, SLOT(
readProject(
const QDomDocument & ) ) );
136 grabGesture( Qt::PinchGesture );
137 viewport()->setAttribute( Qt::WA_AcceptTouchEvents );
154 QList<QGraphicsItem*> list =
mScene->items();
155 QList<QGraphicsItem*>::iterator it = list.begin();
156 while ( it != list.end() )
158 QGraphicsItem* item = *it;
199 if ( index >= 0 && index < (
int ) layers.size() )
245 QgsDebugMsg(
"NOT updating layer set while drawing" );
250 QStringList layerSet, layerSetOverview;
253 for ( i = 0; i < layers.size(); i++ )
263 layerSet.push_back( lyr.
layer()->
id() );
268 layerSetOverview.push_back( lyr.
layer()->
id() );
274 bool layerSetChanged = layerSetOld != layerSet;
277 if ( layerSetChanged )
279 QgsDebugMsg(
"Layers changed to: " + layerSet.join(
", " ) );
286 disconnect( currentLayer, SIGNAL( repaintRequested() ),
this, SLOT(
refresh() ) );
287 disconnect( currentLayer, SIGNAL( screenUpdateRequested() ),
this, SLOT(
updateMap() ) );
302 connect( currentLayer, SIGNAL( repaintRequested() ),
this, SLOT(
refresh() ) );
303 connect( currentLayer, SIGNAL( screenUpdateRequested() ),
this, SLOT(
updateMap() ) );
320 if ( layerSetOvOld != layerSetOverview )
338 disconnect(
mMapRenderer, SIGNAL( destinationSrsChanged() ),
351 connect(
mMapRenderer, SIGNAL( destinationSrsChanged() ),
352 overview, SLOT( destinationSrsChanged() ) );
380 bool logRefresh = settings.value(
"/Map/logCanvasRefreshEvent",
false ).toBool();
388 bool enableBackbufferSetting = settings.value(
"/Map/enableBackbuffer", 1 ).toBool();
398 qDebug() <<
"Enable back buffering: " << enableBackbufferSetting;
399 if ( enableBackbufferSetting )
401 viewport()->setAttribute( Qt::WA_PaintOnScreen,
false );
405 viewport()->setAttribute( Qt::WA_PaintOnScreen,
true );
420 QApplication::setOverrideCursor( Qt::WaitCursor );
439 QApplication::restoreOverrideCursor();
449 QString logMsg =
tr(
"Canvas refresh: %1 ms" ).arg( t.elapsed() );
450 QObject* senderObj = QObject::sender();
453 logMsg +=
tr(
", sender '%1'" ).arg( senderObj->metaObject()->className() );
474 if ( theQPixmap != NULL )
478 painter.begin( theQPixmap );
483 theQPixmap->save( theFileName, theFormat.toLocal8Bit().data() );
491 pixmap->save( theFileName, theFormat.toLocal8Bit().data() );
500 myHeader +=
"0 \r\n";
502 myHeader +=
"0 \r\n";
510 QFileInfo myInfo = QFileInfo( theFileName );
512 QString myWorldFileName = myInfo.absolutePath() +
"/" + myInfo.completeBaseName() +
"." + theFormat +
"w";
513 QFile myWorldFile( myWorldFileName );
514 if ( !myWorldFile.open( QIODevice::WriteOnly ) )
518 QTextStream myStream( &myWorldFile );
519 myStream << myHeader;
555 QgsDebugMsg(
"Empty extent - keeping old extent with new center!" );
626 extent.
scale( 1.05 );
749 rect.
scale( 1.0, &c );
806 QPen pen( Qt::gray );
814 double dx = qAbs(( currentExtent.
xMaximum() - currentExtent.
xMinimum() ) / 4 );
815 double dy = qAbs(( currentExtent.
yMaximum() - currentExtent.
yMinimum() ) / 4 );
861 if ( ! e->isAutoRepeat() )
873 case Qt::Key_PageDown:
886 QgsDebugMsg(
"Ignoring key: " + QString::number( e->key() ) );
922 QgsDebugMsg(
"Ignoring key release: " + QString::number( e->key() ) );
951 if ( e->button() == Qt::MidButton )
983 if ( e->button() == Qt::MidButton )
996 QgsDebugMsg(
"Right click in map tool zoom or pan, last tool is " +
1038 if ( theRenderContext )
1056 mScene->setSceneRect( QRectF( 0, 0, lastSize.width(), lastSize.height() ) );
1071 QGraphicsView::paintEvent( e );
1076 QList<QGraphicsItem*> list =
mScene->items();
1077 QList<QGraphicsItem*>::iterator it = list.begin();
1078 while ( it != list.end() )
1097 QgsDebugMsg(
"Wheel event delta " + QString::number( e->delta() ) );
1109 if ( QgsApplication::keyboardModifiers() )
1119 if ( e->delta() > 0 )
1137 QgsPoint newCenter( mousePos.x() + (( oldCenter.x() - mousePos.x() ) * scaleFactor ),
1138 mousePos.y() + (( oldCenter.y() - mousePos.y() ) * scaleFactor ) );
1142 extent.
scale( scaleFactor, &newCenter );
1187 r.
scale( scaleFactor, ¢er );
1213 QPoint xy = e->pos();
1262 setCursor( Qt::ArrowCursor );
1278 QBrush bgBrush( theColor );
1279 setBackgroundBrush( bgBrush );
1282 palette.setColor( backgroundRole(), theColor );
1283 setPalette( palette );
1287 mScene->setBackgroundBrush( bgBrush );
1292 return mScene->backgroundBrush().color();
1303 QList<QgsMapLayer*> lst;
1308 lst.append( layer );
1348 QgsDebugMsg(
"Setting map units to " + QString::number( static_cast<int>( u ) ) );
1380 QgsDebugMsg(
"QgsMapCanvas connected to " + QString( signal ) );
1404 double dx = qAbs( end.
x() - start.
x() );
1405 double dy = qAbs( end.
y() - start.
y() );
1410 if ( end.
x() < start.
x() )
1413 r.setXMaximum( r.xMaximum() + dx );
1417 r.setXMinimum( r.xMinimum() - dx );
1418 r.setXMaximum( r.xMaximum() - dx );
1421 if ( end.
y() < start.
y() )
1423 r.setYMaximum( r.yMaximum() + dy );
1424 r.setYMinimum( r.yMinimum() + dy );
1429 r.setYMaximum( r.yMaximum() - dy );
1430 r.setYMinimum( r.yMinimum() - dy );
1467 QList<QGraphicsItem*> list =
mScene->items();
1468 QList<QGraphicsItem*>::iterator it = list.begin();
1469 while ( it != list.end() )
1471 QGraphicsItem* item = *it;
1492 QMessageBox::warning(
1495 tr(
"Could not draw %1 because:\n%2",
"COMMENTED OUT" ).arg( mapLayer->
name() ).arg( mapLayer->
lastError() )
1516 QDomNodeList nodes = doc.elementsByTagName(
"mapcanvas" );
1517 if ( nodes.count() )
1519 QDomNode node = nodes.item( 0 );
1525 QgsDebugMsg(
"Couldn't read mapcanvas information from project" );
1533 QDomNodeList nl = doc.elementsByTagName(
"qgis" );
1536 QgsDebugMsg(
"Unable to find qgis element in project file" );
1539 QDomNode qgisNode = nl.item( 0 );
1541 QDomElement mapcanvasNode = doc.createElement(
"mapcanvas" );
1542 qgisNode.appendChild( mapcanvasNode );
1554 r.
scale( scaleFactor );
1579 QgsDebugMsg(
"refreshing after reprojection was enabled" );
1594 bool QgsMapCanvas::event( QEvent * e )
1601 if ( e->type() == QEvent::Gesture )
1606 done =
mMapTool->gestureEvent( static_cast<QGestureEvent*>( e ) );
1612 done = QGraphicsView::event( e );
void unsetMapTool(QgsMapTool *mapTool)
Unset the current map tool or last non zoom tool.
QgsMapCanvasMap * mMap
owns pixmap with rendered map and controls rendering
const QgsMapToPixel * coordinateTransform()
void zoomToSelected(QgsVectorLayer *layer=NULL)
Zoom to the extent of the selected features of current (vector) layer.
void updateCanvasItemPositions()
called on resize or changed extent to notify canvas items to change their rectangle ...
QPoint mouseLastXY
Last seen point of the mouse.
void setRenderingStopped(bool stopped)
virtual QColor canvasColor() const
Read property of QColor bgColor.
A rectangle specified with double values.
Base class for all map layer types.
void render(QPainter *painter, double *forceWidthScale=0)
starts rendering @ param forceWidthScale Force a specific scale factor for line widths and marker siz...
bool isEmpty() const
test if rectangle is empty
void zoomToNextExtent()
Zoom to the next extent (view)
QGraphicsScene * mScene
graphics scene manages canvas items
void zoomWithCenter(int x, int y, bool zoomIn)
Zooms in/out with a given center.
bool isDirty() const
Return the state of the canvas (dirty or not)
void freeze(bool frz=true)
QgsRenderContext * rendererContext()
Accessor for render context.
virtual void setCanvasColor(const QColor &_newVal)
Write property of QColor bgColor.
void enableOverviewMode(QgsMapOverviewCanvas *overview)
double mapUnitsPerPixel() const
Returns the mapUnitsPerPixel (map units per pixel) for the canvas.
int layerCount() const
return number of layers on the map
A widget that displays an overview map.
void setXMaximum(double x)
Set the maximum x value.
void clearExtentHistory()
void resize(QSize size)
resize canvas item and pixmap
QgsMapRenderer * mMapRenderer
all map rendering is done in this class
bool mouseButtonDown
Flag to indicate status of mouse button.
double yMaximum() const
Get the y maximum value (top side of rectangle)
virtual QString lastError()
If an operation returns 0 (e.g.
void zoomByFactor(double scaleFactor)
Zoom with the factor supplied. Factor > 1 zooms out, interval (0,1) zooms in.
void mouseReleaseEvent(QMouseEvent *e)
Overridden mouse release event.
QgsRectangle extent() const
returns current extent
void setExtent(const QgsRectangle &r)
Set the extent of the map canvas.
QString qgsDoubleToString(const double &a)
An abstract class for items that can be placed on the map canvas.
A class that stores visibility and presence in overview flags together with pointer to the layer...
bool hasCrsTransformEnabled()
A simple helper method to find out if on the fly projections are enabled or not.
void setCurrentLayer(QgsMapLayer *layer)
QList< QgsMapLayer * > layers() const
return list of layers within map canvas. Added in v1.5
void moveCanvasContents(bool reset=false)
called when panning is in action, reset indicates end of panning
WheelAction mWheelAction
Mouse wheel action.
void readProject(const QDomDocument &)
called to read map canvas settings from project
bool panSelectorDown
Flag to indicate the pan selector key is held down by user.
QgsMapOverviewCanvas * mMapOverview
map overview widget - it's controlled by QgsMapCanvas
void refresh()
Repaints the canvas map.
void renderComplete(QPainter *)
Emitted when the canvas has rendered.
~QgsMapCanvas()
Destructor.
void keyReleaseEvent(QKeyEvent *e)
Overridden key release event.
QgsMapTool * mapTool()
Returns the currently active tool.
void setPanningOffset(const QPoint &point)
sets current offset, to be called from QgsMapCanvas
void setLayerSet(const QStringList &layers)
change current layer set
A non GUI class for rendering a map layer set onto a QPainter.
void updateContents()
Update contents - can be called while drawing to show the status.
void resizeEvent(QResizeEvent *e)
Overridden resize event.
QgsMapTool * mMapTool
pointer to current map tool
void zoomLastStatusChanged(bool)
Emitted when zoom last status changed.
bool mAntiAliasing
indicates whether antialiasing will be used for rendering
static void logMessage(QString message, QString tag=QString::null, MessageLevel level=WARNING)
add a message to the instance (and create it if necessary)
void updateScale()
Emits signal scaleChanged to update scale in main window.
void mouseDoubleClickEvent(QMouseEvent *e)
Overridden mouse double click event.
QgsMapLayer * mCurrentLayer
current layer in legend
QSize mNewSize
resize canvas size
void setMapTool(QgsMapTool *mapTool)
Sets the map tool currently being used on the canvas.
void enableAntiAliasing(bool flag)
const QString & name() const
Get the display name of the layer.
void paintEvent(QPaintEvent *e)
Overridden paint event.
Perform transforms between map coordinates and device coordinates.
void showError(QgsMapLayer *mapLayer)
show whatever error is exposed by the QgsMapLayer.
A rectangular graphics item representing the map on the canvas.
void clear()
Clear the map canvas.
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
double yMinimum() const
Get the y minimum value (bottom side of rectangle)
double scale()
Get the last reported scale of the canvas.
double xMaximum() const
Get the x maximum value (right side of rectangle)
bool mBackbufferEnabled
If backbuffering is currently enabled.
void setBackgroundColor(const QColor &color)
void zoomNextStatusChanged(bool)
Emitted when zoom next status changed.
QgsMapTool * mLastNonZoomMapTool
previous tool if current is for zooming/panning
bool hasCrsTransformEnabled() const
returns true if projections are enabled for this layer set
void mousePressEvent(QMouseEvent *e)
Overridden mouse press event.
double mapUnitsPerPixel() const
void render()
renders map using QgsMapRenderer to mPixmap
bool mDirty
Flag to track the state of the Map canvas.
void panToSelected(QgsVectorLayer *layer=NULL)
Pan to the selected features of current (vector) layer keeping same extent.
void setLayerSet(QList< QgsMapCanvasLayer > &layers)
void setYMinimum(double y)
Set the minimum y value.
double scale() const
Scale denominator.
void keyReleased(QKeyEvent *e)
Emit key release event.
QPaintDevice & paintDevice()
void mapToolDestroyed()
called when current maptool is destroyed
bool setExtent(const QgsRectangle &extent)
sets extent and checks whether suitable (returns false if not)
void setMapUnits(QGis::UnitType u)
QPaintDevice & canvasPaintDevice()
Accessor for the canvas paint device.
void setMessageAsPlainText(const QString &msg)
bool mPainting
currently in paint event
QString id() const
Get this layer's unique ID, this ID is used to access this layer from map layer registry.
void wheelEvent(QWheelEvent *e)
Overridden mouse wheel event.
virtual QString lastErrorTitle()
If an operation returns 0 (e.g.
void setRenderFlag(bool theFlag)
Whether to suppress rendering or not.
QGis::UnitType mapUnits() const
Get the current canvas map units.
void refresh()
renders overview and updates panning widget
void renderStarting()
Emitted when the canvas is about to be rendered.
A class to represent a point geometry.
void saveAsImage(QString theFileName, QPixmap *QPixmap=0, QString="PNG")
Save the convtents of the map canvas to disk as an image.
void keyPressed(QKeyEvent *e)
Emit key press event.
void updateFullExtent()
updates extent of the layer set
void zoomOut()
Zoom out with fixed factor.
void zoomToPreviousExtent()
Zoom to the previous extent (view)
void xyCoordinates(const QgsPoint &p)
emits current mouse position
bool isDrawing()
true if canvas currently drawing
bool writeXML(QDomNode &theNode, QDomDocument &theDoc)
write settings
QPoint mouseLastXY()
returns last position of mouse cursor
QgsMapLayer * currentLayer()
returns current layer (set by legend widget)
void setWheelAction(WheelAction action, double factor=2)
set wheel action and zoom factor (should be greater than 1)
void selectionChanged(QgsMapLayer *layer)
Emitted when selection in any layer gets changed.
QgsPoint toMapCoordinates(int x, int y) const
bool mDrawing
Flag indicating a map refresh is in progress.
void selectionChangedSlot()
Receives signal about selection change, and pass it on with layer info.
double mWheelZoomFactor
Scale factor multiple for default zoom in/out.
bool mFrozen
Flag indicating if the map canvas is frozen.
QgsRectangle fullExtent()
returns current extent of layer set
Contains information about the context of a rendering operation.
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
void useImageToRender(bool theFlag)
Select which Qt class to render with.
bool isInOverview() const
void setLayerSet(const QStringList &layerSet)
updates layer set for overview
void setYMaximum(double y)
Set the maximum y value.
void writeProject(QDomDocument &)
called to write map canvas settings to project
void panAction(QMouseEvent *event)
Called when mouse is moving and pan is activated.
static QgsProject * instance()
access to canonical QgsProject instance
QgsMapRenderer * mapRenderer()
void zoomToFullExtent()
Zoom to the full extent of all layers.
void enableAntiAliasing(bool flag)
bool mRenderFlag
determines whether user has requested to suppress rendering
A generic message view for displaying QGIS messages.
void zoomScale(double scale)
Zoom to a specific scale.
UnitType
Map units that qgis supports.
const QgsMapToPixel * getCoordinateTransform()
Get the current coordinate transform.
void scaleChanged(double)
Emitted when the scale of the map changes.
void enableAntiAliasing(bool theFlag)
used to determine if anti-aliasing is enabled or not
QgsMapLayer * mapLayer(QString theLayerId)
Retrieve a pointer to a loaded layer by id.
void useImageToRender(bool flag)
void layerStateChange()
This slot is connected to the visibility change of one or more layers.
QgsRectangle extent() const
Returns the current zoom exent of the map canvas.
QgsMapCanvas(QWidget *parent=0, const char *name=0)
Constructor.
void setMapUnits(QGis::UnitType mapUnits)
Set map units (needed by project properties dialog)
void connectNotify(const char *signal)
debugging member invoked when a connect() is made to this object
void crsTransformEnabled(bool)
void setDirty(bool _dirty)
Flag the canvas as dirty and needed a refresh.
void setPanningOffset(const QPoint &point)
QPoint rubberStartPoint
Beginning point of a rubber band.
double width() const
Width of the rectangle.
void zoomIn()
Zoom in with fixed factor.
virtual bool isEditable() const
Returns true if the provider is in editing mode.
QGis::UnitType mapUnits() const
Represents a vector layer which manages a vector based data sets.
virtual void updatePosition()
called on changed extent or resize event to update position of the item
bool readXML(QDomNode &theNode)
read settings
int selectedFeatureCount()
The number of features that are selected in this layer.
double xMinimum() const
Get the x minimum value (left side of rectangle)
QList< QgsRectangle > mLastExtent
recently used extent
void updateFullExtent()
Updates the full extent.
QStringList & layerSet()
returns current layer set
QgsPoint center() const
Center point of the rectangle.
void extentsChanged()
Emitted when the extents of the map change.
std::auto_ptr< CanvasProperties > mCanvasProperties
Handle pattern for implementation object.
void mouseMoveEvent(QMouseEvent *e)
Overridden mouse move event.
QgsMapLayer * layer(int index)
return the map layer at position index in the layer stack
void updateMap()
updates pixmap on render progress
void setXMinimum(double x)
Set the minimum x value.
QgsRectangle layerExtentToOutputExtent(QgsMapLayer *theLayer, QgsRectangle extent)
transform bounding box from layer's CRS to output CRS
void keyPressEvent(QKeyEvent *e)
Overridden key press event.
double height() const
Height of the rectangle.
void dragEnterEvent(QDragEnterEvent *e)
Overridden drag enter event.
QgsPoint toMapPoint(double x, double y) const
void drawExtentRect()
used for overview canvas to reflect changed extent in main map canvas
void panActionEnd(QPoint releasePoint)
Ends pan action and redraws the canvas.
void mapUnitsChanged()
The map units may have changed, so cope with that.
QgsRectangle fullExtent() const
Returns the combined exent for all layers on the map canvas.
void layersChanged()
Emitted when a new set of layers has been received.
QgsRectangle boundingBoxOfSelected()
Returns the bounding box of the selected features.
void mapToolSet(QgsMapTool *tool)
Emit map tool changed event.
void scale(double scaleFactor, const QgsPoint *c=0)
Scale the rectangle around its center point.