0

I'm trying to add a PostGIS layer to my canvas, but when I debug it I see that QgsVectorLayer does not return anything, however that same code was copied from a plugin that I am making and if the connection and creation of the layer works well. It seems that for this type of applications outside of QGIS it should be done in another way but I do not know it.

This is the code I am using

    def cargarPostGIS2(self):
        uri = QgsDataSourceUri()
        uri.setConnection("localhost", "5432", "catastro", "postgres", "postgres")
        uri.setDataSource("catastro", 'municipios', 'mi_shape')
        vlayer = QgsVectorLayer(uri.uri(False), 'municipios', "postgres")
        if vlayer.isValid():
            # Agregar el layer al registro
            QgsProject.instance().addMapLayer(vlayer)
            self.canvas.setLayers([vlayer])

enter image description here

How resolve this problems?

3
1

You may try below code (tested with my own database table using data with EPSG 4326)

Some of the code in the sample can help you for other purposes as it was an existing script I've updated to manage the PostGIS layer part. You may clean some of the code depending of your requirements

import os
import sys
from qgis.core import (QgsApplication, QgsDataSourceUri, QgsFeature,
                       QgsGeometry, QgsProject, QgsVectorLayer)
from qgis.gui import QgsLayerTreeMapCanvasBridge, QgsMapCanvas
from qgis.PyQt.QtCore import Qt

def loadPostGISLayer(canvas):
    uri = QgsDataSourceUri()
    uri.setConnection("localhost", "5432", "catastro", "postgres", "postgres")
    uri.setDataSource("catastro", 'municipios', 'mi_shape')
    vlayer = QgsVectorLayer(uri.uri(), 'municipios', "postgres")
    return vlayer

app = QgsApplication([], True)
# On Linux, didn't need to set it so commented
# app.setPrefixPath("C:/Program Files/QGIS Brighton/apps/qgis", True)
app.initQgis()
canvas = QgsMapCanvas()
canvas.setWindowTitle("PyQGIS Standalone Application Example")
canvas.setCanvasColor(Qt.white)
project = QgsProject.instance()

# Put ne_10m_admin_0_countries.shp and associated files
# in the same place as the script
layer_shp = QgsVectorLayer(os.path.join(os.path.dirname(__file__), "ne_10m_admin_0_countries.shp"), "Natural Earth", "ogr")
if not layer_shp.isValid():
  print("Layer failed to load!")

project.addMapLayer(layer_shp)

postgis_layer = loadPostGISLayer(canvas)
if postgis_layer.isValid():
    # Agregar el layer al registro
    project.addMapLayer(postgis_layer)

canvas.setExtent(layer_shp.extent())
canvas.setLayers([layer_shp, postgis_layer])
canvas.zoomToFullExtent()
canvas.freeze(True)
canvas.show()
canvas.refresh()
canvas.freeze(False)
canvas.repaint()
bridge = QgsLayerTreeMapCanvasBridge(
    project.layerTreeRoot(),
    canvas
)

def run_when_project_saved():
    print('Saved')

project.projectSaved.connect(run_when_project_saved)

project.write('my_new_qgis_project.qgz')

def run_when_application_state_changed(state):
    print('State changed', state)

app.applicationStateChanged.connect(run_when_application_state_changed)

exitcode = app.exec()
QgsApplication.exitQgis()
sys.exit(True)
1

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.