2

I want to create a layer using PyQGIS, then draw a point in a specific place on a map and add some data to the attribute table. Everything went fine, the script below works but no point seems to be displayed on a map canvas. The code below is from the PuQGIS Developer Cookbook (http://docs.qgis.org/2.18/en/docs/pyqgis_developer_cookbook/vector.html#id8) but nonetheless the point is not visible.

What can be the ploblem?

 def create_layer(self, point, values):
    vl = QgsVectorLayer("Point", "Temporary point layer", "memory")
    pr = vl.dataProvider()

    vl.startEditing()

    pr.addAttributes( [ QgsField("ID", QVariant.Int),
                        QgsField("R",  QVariant.Int),
                        QgsField("G", QVariant.Int),
                        QgsField("B", QVariant.Int),
                        QgsField("Class", QVariant.String)] )
    vl.updateFields()

    feat = QgsFeature()
    feat.setGeometry( QgsGeometry.fromPoint(QgsPoint(500253, 8180778)))
    feat.setAttributes([0, int(values[0]), int(values[1]), int(values[2])])
    pr.addFeatures([feat])

    vl.updateExtents()
    vl.commitChanges()
    QgsMapLayerRegistry.instance().addMapLayer(vl)
    layer = iface.setActiveLayer(vl)
    if not layer:
        self.dlg.l_status.setText("Error: Layer failed to load!")
    else:
        QgsMapCanvas().setLayerSet( [ QgsMapCanvasLayer(vl) ] )
        iface.zoomToActiveLayer()

Here is a screenshot. I zoomed to a temporary layer with a point.

enter image description here

  • 1
    Your code seems ok... Maybe is it related to the crs? You didn't specify it when creating the memory layer. – mgri Apr 30 '17 at 15:32
  • 1
    Thank you for the hint. It worked. I write a plugin and implemented this piece of code there to manually select CRS but it seems to be working not as I thought. Thank you very much – NecroSith Apr 30 '17 at 15:44
3

Thanks to hint from @mgri, I found the solution. It was all about CRS. I had to specify CRS programmatically while creating a temporary layer so instead of

vl = QgsVectorLayer("Point", "Temporary point layer", "memory")

I used

vl = QgsVectorLayer("Point?crs=epsg:32645", "Temporary point layer", "memory")

And now everything works fine.

  • Well done! You wrote a good code, though. +1 – mgri Apr 30 '17 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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