1

I'm writing a QGIS plugin in which input data is multiple small polygons taken from an existing memory layer and merge it into one single polygon (not multi) and return it as memory layer.

However, when I try to set a geometry for the new feature (single one in new memory layer) I get TypeError: QgsGeometry.fromPolygon(unknown-type): argument 1 has unexpected type 'list'. Below is my code and comments.

vl is the old layer and vl_combine is the new one, just as pr_combine is the new dataProvider:

      newGeometry = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')

      for feature in vl.getFeatures(): 
          newGeometry = newGeometry.combine(feature.geometry())

      fet_combine = QgsFeature()
    > fet_combine.setGeometry(QgsGeometry.fromPolygon([newGeometry])) # <-- this is the line I get error in

      fet_combine.setAttributes(['just text'])

      pr_combine.addFeatures(fet_combine)

      vl_combine.updateExtents()

      ## Add prepared layer with transparency
      QgsMapLayerRegistry.instance().addMapLayer(vl_combine)
      vl_combine.setLayerTransparency(50)

So what I do:

  • check the print type(newGeometry) and what I get is <class 'qgis._core.QgsGeometry'>.
  • by print newGeometry I see <qgis._core.QgsGeometry object at 0x9db0680>.
  • finally I print newGeometry.asPolygon() and get a structure of [[(16.9102,52.4036), (16.9105,52.4038), (16.9098,52.4034), (16.9102,52.4036)]] (shortened, but should be clear)

I can't think of more ways to troubleshoot, the object seems to be of correct QgsGeometry type. I tried to put newGeometry without [ ] in the > line, but it didn't work too.

1 Answer 1

2

From the doc, it seems that QgsGeometry.fromPolygon() requires a QgsPolygon object as argument. You can create a QgsPolygon object from a QgsGeometry object with the following method: geometry.asPolygon().

Thus, you should replace your faulting line with:

fet_combine.setGeometry(QgsGeometry.fromPolygon( newGeometry.asPolygon() ))
1
  • works, thanks a lot! I thought that if print type() returns QgsGeometry it actually is desired type of geometry.
    – adamczi
    Commented Aug 22, 2016 at 11:23

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.