2

I would like to teach the QGIS map canvas to follow the current row of an attribute table. I found the method QgsAttributeTableView.currentChanged() as possible starting point, but unfortunately it's not a signal but a protected virtual method inherited from QTableView.

So I tried this in a python plugin, but it didn't produce any messages (I think here is explained why):

    def watchTable(self, attTable):

    @pyqtSlot()
    def currentChanged(attTable, current, previous):
        bar = self.iface.messageBar()
        bar.pushMessage('my plugin',
                        'currentChanged: cur {}, prev {}'.format(current, previous),
                        bar.INFO, 5)

    # would this overwrite something existing?
    attTable.currentChanged = currentChanged

Any ideas?

1

I have some success catching the paint event, with Nathan's help. Current code looks like this:

def eventFilter(self, object, event):
    tv = self.followedTable
    if object == tv.viewport() and event.type() == QEvent.Paint:
        ci = tv.currentIndex()
        row = ci.row()
        if row != self.lastRow:
            # this should probably be outside the event filter (emit signal?)
            model = sip.cast(ci.model(), QgsAttributeTableFilterModel)
            fid = model.rowToId(ci)
            layer = model.layer()
            f = QgsFeature()
            layer.getFeatures(QgsFeatureRequest(fid)).nextFeature(f)
            g = f.constGeometry()
            c = g.centroid().asPoint()
            mc = self.iface.mapCanvas()
            ms = mc.mapSettings()
            mc.setCenter(ms.layerToMapCoordinates(layer, c))
            mc.refresh()
            self.lastRow = row
    return False

def watchTable(self, attTable):
    try:
        # here I get crashes/mini dumps
        self.followedTable.viewport().removeEventFilter(self)
    except:
        pass
    self.followedTable = attTable
    self.lastRow = -1
    self.followedTable.viewport().installEventFilter(self)

EDIT: My "Sync map and attribute table" plugin is available in QGIS official plugin repository, marked as experimental.

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.