point_layer = QgsVectorLayer("Point?crs=epsg:4326", "Point Layer", "memory") fields = QgsFields() fields.append(QgsField("name", QVariant.String)) point = QgsPointXY(10, 20) feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPointXY(point)) feature.setAttributes(["my point"]) point_layer.startEditing() point_layer.addFeature(feature) point_layer.commitChanges()
polygon_layer = QgsVectorLayer("Polygon?crs=epsg:4326", "Polygon Layer", "memory") fields = QgsFields() fields.append(QgsField("label", QVariant.String)) points = [QgsPointXY(0, 0), QgsPointXY(10, 0), QgsPointXY(10, 10), QgsPointXY(0, 10), QgsPointXY(0, 0)] feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPolygonXY([[point for point in points]])) feature.setAttributes(["my polygon"]) polygon_layer.startEditing() polygon_layer.addFeature(feature) polygon_layer.commitChanges()Brief Description: The first example adds a point feature to a memory layer named "Point Layer" at coordinates (10, 20) with an attribute named "name" set to "my point". The second example adds a polygon feature to a memory layer named "Polygon Layer" with vertices at (0, 0), (10, 0), (10, 10), and (0, 10) and an attribute named "label" set to "my polygon". Both examples create a new layer in memory and commit the changes. Package Library: The package library used in these examples is the QGIS core library.