4

I am practicing QGIS python API and I made a standalone script to create .qgs file and import some layers from PostGIS database. Now I need to zoom to imported layer but I saw that it is not possible via iface.setActiveLayer(vlayer) and then iface.zoomToActiveLayer() because I cannot use iface for standalone script.

Is there any other way to zoom to an imported layer?

This is what I have done so far:

import subprocess
subprocess.call([r'batch.bat'])
import qgis.core
print('Importovan')
import glob
import os
import sys
from qgis.core import (QgsProject, QgsRasterLayer,QgsVectorLayer,QgsApplication,QgsCoordinateReferenceSystem)
from qgis.gui import QgisInterface,QgsMapCanvas
from PyQt5.QtCore import QFileInfo
from PyQt5.QtSql import *
from qgis.core import QgsDataSourceUri
import qgis.utils
strProjectName = "my_project.qgs"

# start the qgis application
QgsApplication.setPrefixPath(r"C:\OSGeo4W64\apps\qgis", True)
qgs = QgsApplication([], False)
qgs.initQgis()

# start a project
project = QgsProject.instance()

selectedcrs="EPSG:4326"
target_crs = QgsCoordinateReferenceSystem()
target_crs.createFromUserInput(selectedcrs)
project.setCrs(target_crs)

canvas=QgsMapCanvas()
iface=QgisInterface.QgsMapCanvas()
project_path = strProjectName
###############################

db = QSqlDatabase.addDatabase('QPSQL')
# check to see if it is valid
if db.isValid():
    print ("QPSQL db is valid")
    # set the parameters needed for the connection
    db.setHostName('localhost')
    db.setDatabaseName('request')
    db.setPort(int(5433))
    db.setUserName('postgres')
    db.setPassword('postgres')
    uri = QgsDataSourceUri()
    uri.setConnection("localhost", "5433", "request", "postgres", "postgres")
    #open (create) the connection
    if db.open():
        print ("Opened %s" % uri.uri())
        uri.setDataSource ("rodno_razvrstani_podaci", 'statistika_2017', 'wkb_geometry')
        vlayer=QgsVectorLayer (uri .uri(False), 'statistika_2017', "postgres")
        project.addMapLayer(vlayer)
        
    else:
            err = db.lastError()
            print (err.driverText())
db.close()

#This is where script breaks
qgis.utils.iface.setActiveLayer(vlayer)
#iface.zoomToActiveLayer()

###############################

# write the project file
project.write(project_path)

# stop qgis
qgs.exitQgis() 

1 Answer 1

5

You don't need iface to zoom to a layer. It's sufficient to set the map canvas extent as the layer extent.

...
canvas.setExtent(vlayer.extent())    
project.write(project_path)

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.