I try to develop a plugin to add postgis layers to qgis from a plugin as part of learning python.
The code for adding a postgis layer is taken from the cookbook and work fine if I run it from the python console within qgis (If button OK is pressed in dialog box result == 1 and should add my layer to qgis).
But if I run it from my plugin it throws the message NameError: name 'QgsDataSourceURI' is not defined. Why do I get that error running it from the plugin?
Is there a difference how I add a layer from a plugin/inside a function vs from the python console?
def run(self):
"""Run method that performs all the real work"""
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result == 1:
# Do something useful here - delete the line containing pass and
# substitute with your code.
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "test", "postgres", "postgres")
#set database schema, table name, geometry column and optionaly subset(WHERE clause)
uri.setDataSource ("basic", "cities", "geom")
# Defining the layer name and layer type for QGIS?
vlayer=QgsVectorLayer (uri .uri() ,"cities","postgres")
Answer
Because you need to import Python classes before using them. Just write this in the heading of that file:
from qgis.core import QgsDataSourceURI
It's different in the QGIS Python Console because it automatically loads QGIS classes when it's opened.
Note that if you haven't imported the QgsVectorLayer
class yet, you'll get a similar error. Instead of adding a new line, you can list the classes you would like to import from qgis.core
library, this way:
from qgis.core import QgsVectorLayer, QgsDataSourceURI
No comments:
Post a Comment