Geographic Information Systems Asked by appapatil on June 6, 2021
I have .SHP with different attributes like STATE, DISTRICT, SUB-DISTRICT/VILLAGE/PIN NUMBER with geometry. I want to make a dropdown list using those attributes to select STATE then DISTRICT then SUB-DISTRICT AND FINALLY village in QGIS
This solution assumes the following:
As is, this script will unselect any existing selections from the given layer, select the feature that matches the chosen value from the dropdown list, zoom to it, and clear the selection. It happens fast enough, you won't see the feature be selected and unselected.
In my example below, I am using a layer called 'corps' and the field I use is called 'name'. Adjust to your case.
In Project > Properties > Macros, you can adjust the openProject section to this:
def openProject():
from qgis import utils
from qgis.utils import iface
from PyQt5.QtWidgets import QLabel, QComboBox, QPushButton
from qgis.core import QgsProject,QgsLayerTreeNode,QgsLayerTreeGroup
# VARIABLES TO CHANGE
#####################
layername = 'corps'
field = 'name'
#####################
canvas = iface.mapCanvas()
layer = QgsProject.instance().mapLayersByName(layername)[0]
toolBar = iface.addToolBar("Zoom To Feature")
toolBar.setObjectName("Zoom to Feature")
lbl1 = QLabel(iface.mainWindow())
cbo1 = QComboBox(iface.mainWindow())
btn1 = QPushButton(iface.mainWindow())
# Setting up toolbar
lbl1.setText('Zoom to: ')
btn1.setText('GO!')
tbAction = toolBar.addWidget(lbl1)
tbAction = toolBar.addWidget(cbo1)
tbAction = toolBar.addWidget(btn1)
toolBar.setEnabled(True)
cbo1.clear()
features = layer.getFeatures('1=1')
flist = []
for feature in features:
flist.append(feature[field])
flist.sort()
cbo1.addItems(flist)
btn1.clicked.connect(lambda: zoomtofeature(field, cbo1.currentText()))
def zoomtofeature(field, value):
iface.setActiveLayer(layer)
layer.removeSelection()
features = layer.getFeatures(f"{field} = '{value}'")
ids = [i.id() for i in features]
layer.selectByIds(ids)
canvas.zoomToSelected(layer)
layer.removeSelection()
iface.addToolBar(toolBar)
This puts together toolbar elements, loads the values found in the 'name' field, and displays the toolbar.
At this point, if you open another project from this window, the toolbar will persist. Add the following to the closeProject section of the macro script to remove the toolbar as it closes.
def closeProject():
parent = toolBar.parentWidget()
parent.removeToolBar(toolBar)
Once you save the project file, this toolbar should only appear when the project it is saved to is open.
Answered by Nathan Saylor on June 6, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP