PyQGIS – Use Coordinates from Mouse Click for QgsPointXY

coordinatesfields-attributesgeometrypointpyqgis

I can not figure out how to input the coordinates through a mouse click instead of the code below. I am trying to create a temporary layer of a point from a mouse click. Everything seems to work except for that I can not figure the coordinates out.

from qgis.PyQt.QtCore import QVariant

vl = QgsVectorLayer("Point", "POI", "memory")    
pr = vl.dataProvider()
pr.addAttributes([QgsField("ID", QVariant.String)])
vl.updateFields() 
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(10,10)))
f.setAttributes(["1"])

pr.addFeature(f)
vl.updateExtents() 
QgsProject.instance().addMapLayer(vl)

Best Answer

Combining lines in this link and your code, it looks as follows:

from qgis.gui import QgsMapToolEmitPoint
from qgis.PyQt.QtCore import QVariant

def display_point( pointTool ): 

    vl = QgsVectorLayer("Point", "POI", "memory")    
    pr = vl.dataProvider()
    pr.addAttributes([QgsField("ID", QVariant.String)])
    vl.updateFields() 
    f = QgsFeature()
    f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(pointTool[0],pointTool[1])))
    f.setAttributes(["1"])

    pr.addFeature(f)
    vl.updateExtents() 
    QgsProject.instance().addMapLayer(vl)

# a reference to our map canvas 
canvas = iface.mapCanvas() 

# this QGIS tool emits as QgsPoint after each click on the map canvas
pointTool = QgsMapToolEmitPoint(canvas)

pointTool.canvasClicked.connect( display_point )

canvas.setMapTool( pointTool )

After running it in Python Console of QGIS 3, it can be observed in following image, after 10 mouse clicks, there were produced 10 point layers as expected.

enter image description here