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")