我正在尝试将 Postgis 中的层添加到 Qgis 项目中。我的脚本似乎有效,因为我没有错误,但图层没有添加到项目中。我尝试添加的每个表都有一个唯一的键。
这是我的脚本:
uri = QgsDataSourceUri()
try:
uri.setConnection("my_host", "my_port", "my_dbase_name", "my_user", "my_password")
except:
'Unable to connect database !'
uri.setDataSource("my_schema", "my_table", "geom","","my_unique_id")
vlayer = QgsVectorLayer(uri.uri(), "my_layer_name", "my_user_name")
QgsProject.instance().addMapLayer(vlayer)
我不知道问题出在哪里?如果有人提出想法或看到明显的错误......我感兴趣。
谢谢的
您需要检查创建图层时返回的内容,如果发生错误,则会None
。我还认为您需要指定要使用的驱动程序(postgres
(,而不是您的用户名。
我会使用这样的代码:
tablename = "thetable"
geometrycol = "geom"
from qgis.core import QgsVectorLayer, QgsDataSourceUri
uri = QgsDataSourceUri()
uri.setConnection("host", "5432", "db", "user", "pass")
uri.setDataSource ("schema", tablename, geometrycol)
vlayer=QgsVectorLayer (uri.uri(False), tablename, "postgres")
QgsProject.instance().addMapLayer(vlayer)