4

I have a layer which has FID field representing the unique ID of features. In QGIS, there is a Zoom to selected rows button on top of the Attribute Table. It has a shortcut (Ctrl + J) and it doesn't work (at least in my computer). (In ArcGIS, when you double-click a row number in the Attribute table, it zooms to related feature)

Sometimes, it's a waste of time to click the zoom button if considering hundreds of features and I need to speed up the zooming process to save time.

I can display the attribute table using the lines below and get the reference of it.

lyr = QgsProject.instance().mapLayersByName("LAYER_NAME")[0]
attr_table = iface.showAttributeTable(lyr)

Is there any programmatic way to zoom to a feature by clicking FID cell in the Attribute Table in QGIS? How can I add this capability to the Attribute Table?

4

I've found a temporary solution:

layer = QgsProject.instance().mapLayersByName("LAYER_NAME")[0]    
attr_table = iface.showAttributeTable(layer)
table = attr_table.findChildren(QTableView)[0]

def zoom(item):
    """ zooms to feature when clicking FID field """
    x = item.data() # get cell value
    try:
        ID = list(layer.getFeatures('"FID" = ' + x))[0].id()
        iface.mapCanvas().zoomToFeatureIds(layer, [ID])
    # when clicked another/wrong cell, it may throw an error, pass the error.
    except: 
        pass

table.clicked.connect(zoom) # attach zoom method to click event of the table

showAttributeTable returns the reference of the attribute table, and the attribute table contains only one QTableView element which is the object containing all columns and rows. Then, when clicked FID value/cell, it zooms to feature with FID value.

In that script, the main limitation is that I have to open the attribute table using showAttributeTable method. If I open the table using Right click -> Open Attribute Table, clicking FID value doesn't work. Also, when I close the attribute table, attr_table and table objects are deleted. It means that every time I open the table, new objects are created.

enter image description here

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.