I want to select and zoom in features in active QGIS project from external application.

This script do all the things I need, except it does not affect currently running project. It selects and makes zoom to selected but not in opened QGIS project. It shows standalone python window instead of project's.

If I remove last command - qgis.exec_() I see only empty console window - no changes in running project's window.

# coding=UTF-8
from qgis.core import *
from PyQt4.QtCore import QFileInfo
from qgis.core import QgsMapLayerRegistry
from qgis.core import QgsMapLayer
from qgis.gui import QgsMapCanvas,QgsLayerTreeMapCanvasBridge
import os.path

qgis = QgsApplication([], True)

project = QgsProject.instance()
canvas = QgsMapCanvas()
if project.fileName() == "":
    my_file = os.path.isfile(os.path.join('c:\qgis_test','test.qgs'))
    if my_file:

bridge = QgsLayerTreeMapCanvasBridge(project.layerTreeRoot(), canvas, qgis)
layers = QgsMapLayerRegistry.instance().mapLayers()
expr = QgsExpression( "\"name\"='{}'".format('Gothenburg'))

selLayer = layers.items()[0][1]

it = selLayer.getFeatures(QgsFeatureRequest(expr))
ids = [i.id() for i in it]
box = selLayer.boundingBoxOfSelected()


I think I need to create link between QgsApplication in script and currently running project window but don't know how to do it.

  • To clarify, you want reference from a standalone script to an already open QGIS project? – artwork21 Aug 1 '17 at 12:07
  • Yes, I want to do all the things in currently opened project. – Alexd Aug 2 '17 at 9:16

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.