I want to build a custom Toolbar with Plugin Builder 3 for QGIS. I managed to create the necessary folders and files and I can load my UI into QGIS:
The UI looks very simple with only two buttons like this:
Pushbutton1 Pushbutton 2
There is a point layer in QGIS and I want both buttons to work with this layer. The AttributeTable of the point layer consists of elements like: ID, class, description
If I press Pushbutton1 and click at a location on the map canvas I want to create a new feature in the point layer that belongs to class A
If I press Pushbutton2 and click at a location on the map canvas I want to create a new feature in the point layer that belongs to class B
Here is what I tried so far:
my_toolbar.py
# Import necessary modules
from qgis.core import *
from qgis.gui import *
# Define a function to add a new feature to the layer
def add_feature():
# Get the active layer
layer = iface.activeLayer()
# Get the layer's feature count
count = layer.featureCount()
# Create a new feature
feature = QgsFeature(layer.fields())
feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0, 0)))
feature.setAttribute('ID', count + 1)
feature.setAttribute('class', 'class_entry1')
# Add the feature to the layer
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
# Create a new button in QGIS
button = pushButton1('Add Feature')
# Connect the button to the add_feature function
button.clicked.connect(add_feature)
# Add the button to the QGIS toolbar
iface.addToolBarWidget(button)
The code is for only one button so far to test it, but if I run the code nothing happens, I don't even get any errors that help me find a solution. Once the code works, I just want to repeat it for the 2nd button. I also don't know how I can change the code that the user can define a point by clicking at the canvas.