Implementing QAbstractProxyModel methods

2.2k views Asked by At

I have a QSqlTableModel which has approximately this structure:

| ID |  Name  |
---------------
|  0 |  Xxxx  |
|  2 |  Yyyy  |
|  5 |  Zzzz  |

As you can see, IDs (which are unique) are sequential, but can be skipped; the available range is always from 0 to 1023. I need to create a table that fills the gaps up to the 1024 rows, without changing the source model layout. The final result will be something like this:

|  0 |  Xxxx  |
|    |        |
|  2 |  Yyyy  |
|    |        |
|    |        |
|  5 |  Zzzz  |
      ...
|1023|  Xyz   |

The "blank" items will not be editable, but the user will be able to use drag&drop to reorder (which will be implemented internally interfacing with the SQL model) and add/remove items, while always keeping the table size to 1024 rows.

I tried implementing QAbstractProxyModel, but I have some problems. For instance, the flags are not respected and every item is not editable, nor selectable. Even if I specifically return ItemIsEnabled|ItemIsSelectable|ItemIsEditable, nothing changes. Also, clicking on items gives strange results for header highlighting.

I suppose I'm doing something wrong with mapToSource/mapFromSource, but I'm not sure.

This is an example I made using QStandardItemModel instead of QSqlTableModel (the resulting behavior is the same) with 4 rows, and a Proxy showing 6 rows.

class BaseModel(QtGui.QStandardItemModel):
    def __init__(self):
        QtGui.QStandardItemModel.__init__(self)
        for id, name in [(1, 'One'), (2, 'Two'), (3, 'Three'), (5, 'Five')]:
            idItem = QtGui.QStandardItem()
            idItem.setData(id, QtCore.Qt.DisplayRole)
            nameItem = QtGui.QStandardItem(name)
            self.appendRow([idItem, nameItem])


class ProxyModel(QtCore.QAbstractProxyModel):
    def data(self, index, role):
        source = self.mapToSource(index)
        if source.isValid():
            return source.data(role)
        return None

    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
            return str(section + 1)
        return QtCore.QAbstractProxyModel.headerData(self, section, orientation, role)

    def setData(self, index, value, role):
        return self.sourceModel().setData(self.mapToSource(index), value, role)

    def index(self, row, column, parent=None):
        res = self.sourceModel().match(self.sourceModel().index(0, 0), QtCore.Qt.DisplayRole, row, flags=QtCore.Qt.MatchExactly)
        if res:
            return res[0].sibling(res[0].row(), column)
        return self.createIndex(row, column)

    def parent(self, index):
        return self.sourceModel().index(index.row(), index.column()).parent()

    def flags(self, index):
        source = self.mapToSource(index)
        if source.isValid():
            return source.flags()
        return QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable

    def rowCount(self, index):
        return 6

    def columnCount(self, index):
        return 2

    def mapToSource(self, index):
        res = self.sourceModel().match(self.sourceModel().index(0, 0), QtCore.Qt.DisplayRole, index.row(), flags=QtCore.Qt.MatchExactly)
        if res:
            return res[0].sibling(res[0].row(), index.column())
        return QtCore.QModelIndex()

    def mapFromSource(self, index):
        if index.row() < 0:
            return QtCore.QModelIndex()
        row = self.sourceModel().index(index.row(), 0).data()
        return self.createIndex(row, index.column())


class Win(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        layout = QtWidgets.QGridLayout()
        self.setLayout(layout)
        self.model = BaseModel()
        self.proxy = ProxyModel()
        self.proxy.setSourceModel(self.model)
        table = QtWidgets.QTableView()
        table.setModel(self.proxy)
        layout.addWidget(table)
1

There are 1 answers

6
eyllanesc On BEST ANSWER

It is not necessary to implement a QAbstractProxyModel, in this case it is sufficient to use a QIdentityProxyModel:

class ProxyModel(QtCore.QIdentityProxyModel):
    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
            return str(section + 1)
        return QtCore.QIdentityProxyModel.headerData(self, section, orientation, role)

    def setData(self, index, value, role=QtCore.Qt.DisplayRole):
        if index.column() == 0:
            if not (0 <= int(value) < self.rowCount()) :
                return False
        return QtCore.QIdentityProxyModel.setData(self, index, value, role)

    def rowCount(self, index=QtCore.QModelIndex()):
        return 6

    def index(self, row, column, parent=QtCore.QModelIndex()):
        return self.createIndex(row, column)

    def mapFromSource(self, sourceIndex):
        if sourceIndex.isValid()  and 0 <= sourceIndex.row() < self.rowCount():
            ix = self.sourceModel().index(sourceIndex.row(), 0)
            return self.index(int(ix.data()), sourceIndex.column())
        return QtCore.QModelIndex()

    def mapToSource(self, proxyIndex):
        res = self.sourceModel().match(self.sourceModel().index(0, 0), QtCore.Qt.DisplayRole, proxyIndex.row(), flags=QtCore.Qt.MatchExactly)
        if res:
            return res[0].sibling(res[0].row(), proxyIndex.column())
        return QtCore.QModelIndex()