2

I have a polygon shapefile (p_cities) and I want to present a simple GUI to the user to select a city from a combobox and that city will be highlighted & zoomed in.

The following code does it for the first city appearing in the combobox, but it does not continue working even if I change my selection in the combobox:

from PyQt4.QtGui import *


lyrName = "p_cities"
lyr = QgsMapLayerRegistry.instance().mapLayersByName(lyrName)[0]
idx = lyr.dataProvider().fieldNameIndex( 'name' ) 
uv = lyr.dataProvider().uniqueValues( idx )
cb = QComboBox()
cb.addItems( uv )
cb.show()    
cityName = cb.currentText()

c = lyr.getFeatures(QgsFeatureRequest().setFilterExpression(u' "name" ILIKE \'%s\' ' %cityName))
lyr.setSelectedFeatures([s.id() for s in c])
iface.mapCanvas().zoomToSelected()

It seems that I need to dig into the signals and slots and use "currentIndexChanged" accordingly. However, it would also be great if I could learn doing it in procedural programming.

3

It's not a big deal, you just have to create a function for the zoom & highlight action and connect it to your comboBox.

The following code should works:

def zoomTo():
    cityName = cb.currentText()
    c = lyr.getFeatures(QgsFeatureRequest().setFilterExpression(u' "name" ILIKE \'%s\' ' %cityName))
    lyr.setSelectedFeatures([s.id() for s in c])
    iface.mapCanvas().zoomToSelected()

from PyQt4.QtGui import *
lyrName = "p_cities"
lyr = QgsMapLayerRegistry.instance().mapLayersByName(lyrName)[0]
idx = lyr.dataProvider().fieldNameIndex( 'name' ) 
uv = lyr.dataProvider().uniqueValues( idx )
cb = QComboBox()
cb.addItems( uv )
cb.show()

cb.currentIndexChanged.connect(zoomTo)

Your Answer

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

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