I am new to QGIS and trying different things. A Python script (link), which is running perfectly in QGIS Python console but I want it to run as a QGIS plugin. I am trying to do but getting confused about where to write my script logic in Plugin file. I copied the code below for reference which I want into Python plugin.
class TestEditTool(QgsMapToolEdit):
def __init__(self, canvas):
self.canvas = canvas
QgsMapToolEdit.__init__(self, self.canvas)
self.rb = QgsRubberBand(self.canvas, QgsWkbTypes.LineGeometry)
self.rb.setStrokeColor(QColor('Red'))
self.rb.setWidth(2.0)
self.fixed_points = []
def canvasReleaseEvent(self, event):
click_point = event.snapPoint()
if event.button() == Qt.LeftButton:
if len(self.fixed_points) < 1:
if not event.isSnapped():
iface.messageBar().pushMessage('Edit Error', 'Start point of line feature \
must be snapped to point layer', level=Qgis.Warning, duration=3)
else:
self.fixed_points.append(QgsPoint(click_point))
else:
self.fixed_points.append(QgsPoint(click_point))
elif event.button() == Qt.RightButton:
if self.fixed_points:
if not event.isSnapped():
iface.messageBar().pushMessage('Edit Error', 'End point of line feature \
must be snapped to point layer', level=Qgis.Warning, duration=3)
else:
self.fixed_points.append(QgsPoint(click_point))
new_line = QgsLineString(self.fixed_points)
geom = QgsGeometry().fromPolyline(new_line)
### Add Features here
layer = iface.activeLayer()
if layer.isEditable():
feat = QgsFeature()
feat.setGeometry(geom)
feat.setFields(layer.fields())
iface.openFeatureForm(layer, feat, False)
layer.addFeature(feat)
layer.triggerRepaint()
###
self.clean_up()
def canvasMoveEvent(self, event):
if self.fixed_points:
self.rb.reset()
if len(self.fixed_points) == 1:
pt1 = self.fixed_points[0]
pt2 = QgsPoint(event.snapPoint())
rb_line = QgsLineString(pt1, pt2)
self.rb.setToGeometry(QgsGeometry().fromPolyline(rb_line), QgsProject().instance().crs())
else:
rb_line = QgsLineString(self.fixed_points)
rb_line.addVertex(QgsPoint(event.snapPoint()))
self.rb.setToGeometry(QgsGeometry().fromPolyline(rb_line), QgsProject().instance().crs())
self.rb.show()
def clean_up(self):
self.rb.reset()
self.fixed_points.clear()