pythonpyqtqmltableviewqmodelindex

Map QML TableView row on activated back to QModelIndex


I have a QML TableView where I display some data from a model implementing QAbstractItemModel. But instead of using it directly I wrap it in a QSortFilterProxyModel for the sorting and filtering features.

Now if I e.g. have a heavily filtered view and activate a row I want to do something with the activated model item. But the onActivated() handler only gives me the row number I clicked on but I think I need the QModelIndex to query the underlying model for the item. I also can't implement something like model.get(row) since the model has now mapping of rows to indexes.


Solution

  • I figured out how it is supposed to work. You implement index and data in your custom sortfilterproxymodel like this:

    @pyqtSlot(int, int, result=QModelIndex)
    @pyqtSlot(int, int, QModelIndex, result=QModelIndex)
    def index(self, row, column, parent=QModelIndex()):
        return super().index(row, column, parent)
    
    @pyqtSlot(QModelIndex, int, result=QVariant)
    def data(self, index, role=Qt.DisplayRole):
        return super().data(index, role)
    

    Now you can call e.g. like this in QML

    property var qt_UserRole: 256 // FIXME: Qt.UserRole is not exported
    model.data(model.index(row, 0), qt_UserRole + 1)