2

The following code is used to test if a selected object from layer A is inside an object from another layer B. Depending on the result, a window is displayed and indicates the answer.

The object selected in layer A has several attributes including its name 'geo_parcelle' I don't know how to display it. I replaced ???? by layer2.getFeatures(geo_parcelle) but it doesn't work. does anyone have an idea?

from qgis.PyQt import QtWidgets

layer1 = QgsProject.instance().mapLayersByName('1')[0] 
layer2 = QgsProject.instance().mapLayersByName('2')[0]

for feature in layer1.getSelectedFeatures(): 
    if feature.geometry().within(layer2.aggregate(aggregate=19,fieldOrExpression='$geometry')[0]):
        QtWidgets.QMessageBox.information(None, 'la parcelle ',  ???? + 'IN Z')
    else:
        QtWidgets.QMessageBox.information(None, 'la parcelle ',  ???? + 'OUT Z')

1 Answer 1

4

If the attribute you are trying to access is in your layer A/layer1, then you already have a reference to the feature and you can access its 'geo_parcelle' attribute with feature['geo_parcelle'] and use string formatting to insert this value into your message box information string like this:

from qgis.PyQt import QtWidgets

layer1 = QgsProject.instance().mapLayersByName('1')[0] 
layer2 = QgsProject.instance().mapLayersByName('2')[0]

for feature in layer1.getSelectedFeatures(): 
    if feature.geometry().within(layer2.aggregate(aggregate=19,fieldOrExpression='$geometry')[0]):
        QMessageBox.information(None, 'la parcelle', f'{feature["geo_parcelle"]} IN Z')
    else:
        QMessageBox.information(None, 'la parcelle', f'{feature["geo_parcelle"]} OUT Z')
2
  • Thank you ! I replaced the f' with the str function and it works perfectly. [1]: i.sstatic.net/I9Rxd.jpg
    – fcka
    Sep 20, 2022 at 12:05
  • @fcka, you don't need the str() function here. You can see in your image that you are getting the curly braces showing up in your string. You should read up on Python f-strings: realpython.com/python-f-strings/…. With f-string formatting, the statement inside the curly braces is evaluated and the returned value is inserted into the string.
    – Ben W
    Sep 24, 2022 at 13:29

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.