4

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().

2 Answers 2

6
+50

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.

1
  • classes to be imported for this one please Commented Aug 13, 2019 at 5:20
3

You can also use iface.actionMapTips().trigger() and in QGIS 3.x for layer field description use layer.setDisplayExpression('field_name')

Also if you want to create a function to control to check and uncheck use that:

iface.actionMapTips().setChecked(True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.