I am opening a QGIS project using the following snippet:

new_project = False
if not os.path.exists(self.qgis_project_path):
    prj_template_path = os.path.join(self.qgis_template_path, 'project.qgs')
    shutil.copy(prj_template_path, self.qgis_project_path)
    new_project = True    #load default layers because the user is opening a particular project for the first time

if new_project:
    for layername in self._settings['vector_layers']:
        uri = QgsDataSourceURI()
        uri.setConnection(self._settings['db_host'], self._settings['db_port'], self._settings['db_dbase'], self._settings['db_user'], self._settings['db_pass'])
        uri.setDataSource('p_{}'.format(self._project[2].replace('-', '_')), layername, 'geom', '')

        lyr = self._iface.addVectorLayer(uri.uri(), layername, 'postgres')
        if not lyr.isValid():
            QgsMessageLog.logMessage(u'Failed to open the layer: {}'.format(layername), 'Skytek')
        styleload = lyr.loadNamedStyle(os.path.join(self.style_path, '{}.qml'.format(layername)))
        if not styleload[1]:
            QgsMessageLog.logMessage(u'Error loading style: {}'.format(layername), 'Skytek')

    for raster in self._settings['raster_layers']:

    self._iface.mapCanvas().setDestinationCrs(self._local) #qgis3: QgsProject.instance().setCrs(self._local)
    self._iface.mapCanvas().setMapUnits(QGis.Meters) #qgis3: QgsProject.instance().setDistanceUnits(QgsUnitTypes.Meters)

I don't understand why every SECOND time I call this, the loaded project shows no layers in the legend. The project file is copied to the user folder only the first time, also the layers are created only the first time. The only line that is called subsequently is:


And like I said, layers are added to the legend only every second time the project is read. I noticed when I reopen an existing project file in QGIS with "Project->Open project" it works as expected.

  • What happens if you add QgsProject.instance().clear() before QgsProject.instance().read(QFileInfo(self.qgis_project_path))? – Joseph Jul 7 '17 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.