Tuesday 20 June 2017

qgis - Toggle Map Tips with PyQGIS?


I want to display "map tips" in QGIS with python for my custom map canvas QgsMapCanvas().


How can I do this? I can switch manually with View/Map Tips but it won't work with my custom canvas in my plugin, it works only with iface.mapCanvas().



Answer



Not sure if there's another way, but this is how I've implemented it.


You need these three functions (make sure you import the required QGIS and Qt4 classes before):


def createMapTips( self ):
""" Create MapTips on the map """
self.timerMapTips = QTimer( self.canvas )

self.mapTip = QgsMapTip()
self.connect( self.canvas, SIGNAL( "xyCoordinates(const QgsPoint&)" ),
self.mapTipXYChanged )
self.connect( self.timerMapTips, SIGNAL( "timeout()" ),
self.showMapTip )

def mapTipXYChanged( self, p ):
""" SLOT. Initialize the Timer to show MapTips on the map """
if self.canvas.underMouse(): # Only if mouse is over the map
# Here you could check if your custom MapTips button is active or sth

self.lastMapPosition = QgsPoint( p.x(), p.y() )
self.mapTip.clear( self.canvas )
self.timerMapTips.start( 750 ) # time in milliseconds

def showMapTip( self ):
""" SLOT. Show MapTips on the map """
self.timerMapTips.stop()

if self.canvas.underMouse():
# Here you could check if your custom MapTips button is active or sth

pointQgs = self.lastMapPosition
pointQt = self.canvas.mouseLastXY()
self.mapTip.showMapTip( self.layer, pointQgs, pointQt,
self.canvas )

You would also need to set a layer, and probably a display field:


self.layer = layer # For MapTips
self.layer.setDisplayField('NMG')

Finally, initialize the createMapTips function, for example, after you set your base layer and its display field.



self.createMapTips()

You should be able to see map tips on your custom mapCanvas like this:


enter image description here


Notice that you could need some GUI controls to help users use and configure map tips. For example, a button to enable/disable them and a comboBox for users to choose the display field, but, of course, it would depend on your use case.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...