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?

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Dec 30, 2020 at 14:26
3
  • this way if it loads the shp well, but the postgis layer does not vlayer = QgsVectorLayer("provincias.shp", "provincias","ogr") Commented Dec 30, 2020 at 15:06
  • 1
    Would this help? gis.stackexchange.com/questions/28743/… Commented Dec 30, 2020 at 21:43
  • Thank you very much for your answer, but the connection parameters are fine because as a plugin this code works fine but as an independent application of qgis it does not Commented Jan 2, 2021 at 3:46

1 Answer 1

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)
answered Jan 15, 2021 at 0:44
1
  • Thank you very much Thomas, I will test the code Commented Jan 15, 2021 at 14:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.