Monday 22 July 2019

pyqgis - Failed to create memory layers in QGIS application on Linux


I have written a python class which reads properties of map layers from an XML file and creates appropriate memory layers. I have developed and tested this code with QGIS 2.8.2 on a Windows 7 machine (importing the class at the python console and calling the class methods). As the module should be used in a Linux environment I did the same successfully with QGIS 2.8.2 on CentOs 7 - all map layers were successfully created and symbolized.


Then I refactored the code to fit in the framework of a QGIS standalone application. There are major problems with threads and such stuff, but the app starts and comes up with all layers created, and working methods.


Now comes the strange part. In the standalone CentOs version the creation of memory layers doesn't work - layers are not valid. Even a simplified test without field definitions, no crs doesn't work.


layer = QgsVectorLayer(type + '?crs=EPSG:' + str(epsg) + fields, layer_name, 'memory')


Hundreds of lines of code before and after this line are the same in all versions. Has anybody an idea how to handle this problem? Maybe a bug?



Answer



To avoid "layer is not valid" errors you should carefully set your QGIS prefix path. The prefix path must be set to let QGIS know where to find resources such as data providers and the reference system database. If you look at your QGIS installation, you should be able to access lib/qgis/plugins on Unix (or just plugins on Windows), relative to the prefix path. For instance:



  • On my Ubuntu Linux the prefix path is: /usr, because providers are at /usr/lib/qgis/plugins.

  • On Windows I can access C:\\OSGeo4W\\apps\\qgis\\plugins\\, so the prefix path should be C:\\OSGeo4W\\apps\\qgis\\


For reference, have a look at Viewer not displaying the data in my standalone PyQGIS Application and Getting random values from geometryType() in a standalone PyQGIS script if you want more information on this matter.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...