Reputation: 5
I try to add from my db postgis to my QGIS interface a table, I'm using a script with the good parameters. But my problem is when I run my function my QGIS bugs and close.
from qgis.core import *
from qgis.core import QgsProject
from PyQt5.QtCore import QFileInfo
from qgis.core import QgsVectorLayer, QgsDataSourceUri
from qgis.utils import *
def run_script(iface):
uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "Base_test", "user", "passeword")
uri.setDataSource("public", "BPE", "geom")
layer = QgsVectorLayer(uri.uri(), "bpe", "user")
if not layer.isValide():
print("Layer %s did not load" %layer.name())
QgsProject.instance().addMapLayer(layer)
it say me that the layer did not load. and QGIS need to be restarted after that.
can someone help me please.
I'm using QGIS 3.10
Upvotes: 0
Views: 2679
Reputation: 36
Try this code:
from qgis.core import *
from qgis.core import QgsProject
from PyQt5.QtCore import QFileInfo
from qgis.core import QgsVectorLayer,
QgsDataSourceUri
from qgis.utils import *
def run_script(iface):
uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "Base_test",
"user", "passeword")
uri.setDataSource("public", "BPE", "geom")
layer = QgsVectorLayer(uri.uri(), "bpe", "postgres")
if not layer.isValid():
print("Layer %s did not load" %layer.name())
QgsProject.instance().addMapLayer(layer)
run_script()
if not layer.isValide()
-->if notlayer.isValid()
layer = QgsVectorLayer(uri.uri(), "bpe", "user")
--> layer=QgsVectorLayer(uri.uri(), "bpe", "postgres")
run_script()
Check the Documentation: https://qgis.org/pyqgis/3.0/core/Vector/QgsVectorLayer.html
Cheers
Upvotes: 0