I would like to display the value of a raster (at least one band) as a tooltip next to the mouse in Qgis.
The process would be :
- I select the raster layer
- when I move the cursor over the map (or maybe each time I click with the mouse),I can see the value next to the cursor.
I know the plugin ValueTool which is very useful for debug purposes but not so easy to use in order to analyse the data. It is often difficult to point at the right place with the mouse and at the same time to read the value in the plugin.
Answer
One way of doing it is creating your own Map Tool and setting a QTimer (as QGIS does for MapTips) on mouse move events to show the tooltip. The following code illustrates it (works if you run it in the QGIS Python Console).
from qgis.core import QgsRasterLayer, QgsRaster
from qgis.gui import QgsMapToolEmitPoint
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QToolTip
class TooltipRasterMapTool(QgsMapToolEmitPoint):
def __init__(self, canvas):
self.canvas = canvas
QgsMapToolEmitPoint.__init__(self, self.canvas)
self.timerMapTips = QTimer( self.canvas )
self.timerMapTips.timeout.connect( self.showMapTip )
def canvasPressEvent(self, e):
pass
def canvasReleaseEvent(self, e):
pass
def canvasMoveEvent(self, e):
if self.canvas.underMouse(): # Only if mouse is over the map
QToolTip.hideText()
self.timerMapTips.start( 700 ) # time in milliseconds
def deactivate(self):
self.timerMapTips.stop()
def showMapTip( self ):
self.timerMapTips.stop()
if self.canvas.underMouse():
rLayer = iface.activeLayer()
if type(rLayer) is QgsRasterLayer:
ident = rLayer.dataProvider().identify( self.toMapCoordinates(self.canvas.mouseLastXY()), QgsRaster.IdentifyFormatValue )
if ident.isValid():
text = ", ".join(['{0:g}'.format(r) for r in ident.results().values() if r is not None] )
else:
text = "Non valid value"
QToolTip.showText( self.canvas.mapToGlobal( self.canvas.mouseLastXY() ), text, self.canvas )
tooltipRaster = TooltipRasterMapTool( iface.mapCanvas() )
iface.mapCanvas().setMapTool( tooltipRaster ) # Use your Map Tool!
Test plugin
Since a plugin would be much more convenient, I've created this basic test plugin ready to use, there you find installation instructions as well.

No comments:
Post a Comment