10

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")
1
  • I'm trying to use your pattern to add PostGIS layer in python console QGIS but unsuccessfully - "NameError: name 'self' is not defined"( . Do you mind telling me please what's wrong? What self mean (I'm not very good in python). Here is my code gis.stackexchange.com/questions/245985/…
    – Jane
    Commented Jul 1, 2017 at 9:57

1 Answer 1

10

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
2
  • 2
    Sorry for the late reply i just had opportunity to try it out and it worked great! Also thank you for explaining how it is possible to list classes from one library, that was also new to me. Best Regards
    – geogrow
    Commented Jan 4, 2016 at 7:36
  • 2
    In QGIS 3, it is renamed to QgsDataSourceUri. Commented Dec 7, 2018 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.