3

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.

1 Answer 1

0

You should create a widget with two QPushButton on it, and then call show() to display the widget:

btn1 = QPushButton('Add Feature for Layer1')
btn2 = QPushButton('Add Feature for Layer2')
gui = QWidget()
vbl = QVBoxLayout()
vbl.addWidget(btn1)
vbl.addWidget(btn2)
gui.setLayout(vbl)

# Define a function to add a new feature to the layer
def add_feature():
    # add your code here
    ...
    
btn1.clicked.connect(add_feature)
gui.show()

Run this code in your QGIS python editor. Now you can test it by checking the message given in the LogMessages>Python Error Window:

enter image description here

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.