3

I have a snippet that intersects two map layers (blockLayer and ogLayer) in QGIS; and prints out when a bad geometry prevents the intersection from occurring. It builds a subclass from QgsProcessingFeedback, based on the answer posted here by @ndawson.

Here's the code:

class MyFeedBack(QgsProcessingFeedback): # create a subclass from the QgsProcessingFeedback class
    def reportError(self, error, fatalError=False): # QgsProcessingFeedback.reportError() is a method 
        if "invalid geometry" in error:
            featNum = error.split("(")[1].split(")")[0]
            print("{} has bad geometry".format(featNum))
            
blockLayer = QgsProject.instance().mapLayersByName("harvestApprovals")[0]
ogLayer = QgsProject.instance().mapLayersByName('Boundary old growth .gdb layer')[0]

#feedback = QgsProcessingFeedback.reportError(self, error, fatalError=False)
#feedback = QgsProcessingFeedback.reportError(error, fatalError=False)

feedback = QgsProcessingFeedback() # instantitate the QgsProcessingFeedback class
print(feedback)

params = {'INPUT':blockLayer,'OVERLAY':ogLayer,'OUTPUT':'TEMPORARY_OUTPUT'}
rslt = processing.run("native:intersection", params, feedback=MyFeedBack())

print("\nDone!")

I'd prefer to create a list to add those numbers to, so as to know which geometries need repair. I'm just not sure how (or if it's possible) to build a list within an instance of a class, and somehow return that list from the class.

Is there some way I could myList.append(featNum) as the errors are encountered, then get myList back after the process has run?

1 Answer 1

2

When I run your script, print statement never run although I get an error. Thus, I couldn't test it. But the following way should work for you.

  • Add a variable (myList = []) to root scope.
  • Use it in reportError method with global keyword.
myList = []

class MyFeedBack(QgsProcessingFeedback): 
    def reportError(self, error, fatalError=False): 
        if "invalid geometry" in error:
            featNum = error.split("(")[1].split(")")[0]

            global myList
            myList.append(featNum)

#
# other lines
#

print(myList)
print("\nDone!")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.