简体   繁体   English

使用QGIS为Python插件调用QgsDataSourceUri

[英]calling QgsDataSourceUri with QGIS for python plugin

TLDR : using QGIS, I'm trying to develop a python plugin to update a database. TLDR:使用QGIS,我正在尝试开发一个python插件来更新数据库。 Unfortunately I get immediatly an error : Traceback (most recent call last): File "", line 1, in NameError: name 'QgsDataSourceUri' is not defined 不幸的是,我立即收到一个错误:追溯(最近一次调用最近):NameError中文件“”的第1行:未定义名称'QgsDataSourceUri'

More detailed: 更详细:

I work on QGIS2.18 to develop a plugin to update some data located on a postgres database. 我使用QGIS2.18开发一个插件来更新位于postgres数据库上的某些数据。 for this, I want to use this kind of code: 为此,我想使用这种代码:

from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtCore import QSettings
from PyQt4.QtCore import QSettings
from qgis.core import QgsVectorLayer, QgsDataSourceURI

uri = QgsDataSourceUri()

# set host name, port, database name, username and password
uri.setConnection(hote_IP, "5432", base_de_donnee, utilisateur,     mot_de_passe)
# set database schema, table name, geometry column and optionally
# subset (WHERE clause)
#uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")

uri.setDataSource("", sql, "geom", "", "gid")
vlayer = QgsVectorLayer(uri.uri(), zapm, "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

(I got the code from the net, I'll adapt it later on) (我从网上获得了代码,稍后将对其进行修改)

My problem : when I try to run this code on the Python console of QGIS, I immediatly get the error 我的问题:当我尝试在QGIS的Python控制台上运行此代码时,我立即收到错误

Traceback (most recent call last): File "", line 1, in NameError: name 'QgsDataSourceUri' is not defined 追溯(最近一次呼叫最近):NameError中文件“”的第1行:未定义名称'QgsDataSourceUri'

even when I only run the import and the line uri = QgsDataSourceUri() , I get the same error message. 即使当我仅运行导入并且行uri = QgsDataSourceUri()时 ,我也会收到相同的错误消息。

I have not been able to find out how to correct this issue. 我还没有找出如何解决此问题的方法。

problem of installation of QGIS? QGIS的安装问题? of python? 的python? bad imports? 进口不良?

Config: qgis 2.18.20 python 3.6.5 配置:qgis 2.18.20 python 3.6.5

If anyone has an idea on how to solve this, I would be really glad. 如果有人对如何解决这个问题有想法,我将非常高兴。

Thanks, Erwann 谢谢,Erwann

You simply are using the wrong class name. 您只是使用了错误的类名。 It should be uri = QgsDataSourceURI() instead of uri = QgsDataSourceUri() because you've imported QgsDataSourceURI and not QgsDataSourceUri 它应该是uri = QgsDataSourceURI()而不是uri = QgsDataSourceUri()因为您已导入QgsDataSourceURI而不是QgsDataSourceUri

QGIS and QT Python classes are case-sensitive. QGIS和QT Python类区分大小写。 You can confirm the exact syntax looking at QGIS 2.18 related API . 您可以查看与QGIS 2.18相关的API来确定确切的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM