从 QAbstractTableModel class 中访问视图和代理模型?

Access view and proxy model from within QAbstractTableModel class?

使用 QTableViewQAbstractTableModel,我希望能够 select 一个 table 中的多个单元格并进行编辑影响所有这些 select编细胞。这就是我目前的做法,涉及将 view (QTableView) 和 proxy_model (QSortFilterProxyModel) 传递到 class,以便我可以访问他们(为了获取适当的行和列):

import sys
from pprint import pprint

try:
    from PySide2 import QtWidgets, QtCore
except ImportError:
    from PyQt5 import QtWidgets, QtCore


class MyTableModel(QtCore.QAbstractTableModel):
    def __init__(self,
                view,
                proxy_model,
                table_data,
                parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)

        self.table_data = table_data
        self.view = view
        self.proxy_model = proxy_model

    def rowCount(self, parent):
        return len(self.table_data)

    def columnCount(self, parent):
        return len(self.table_data[0])

    def flags(self, index):
        # Original, inherited flags:
        original_flags = super(MyTableModel, self).flags(index)

        return original_flags | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            item = index.internalPointer()

            if item is not None:
                print(item)
            value = self.table_data[row][column]

            return value

        return None

    def setData(self, index, value, role=QtCore.Qt.EditRole):
        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()

            selection_model = self.view.selectionModel()
            selected_indexes = selection_model.selectedIndexes()

            for selected_index in selected_indexes:

                mapped_index = self.proxy_model.mapToSource(selected_index)
                selected_row = mapped_index.row()
                selected_column = mapped_index.column()

                self.table_data[selected_row][selected_column] = value
                pprint(self.table_data)

                self.dataChanged.emit(index, selected_index)  # from, to

            return True

        return False


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    table_data = [['one', 'two', 'three'], ['four', 'five', 'six']]

    view = QtWidgets.QTableView()
    proxy_model = QtCore.QSortFilterProxyModel()
    model = MyTableModel(view=view, proxy_model=proxy_model, table_data=table_data)

    proxy_model.setSourceModel(model)
    proxy_model.setDynamicSortFilter(True)

    view.setModel(proxy_model)
    view.setSortingEnabled(True)  # requires proxy model
    view.sortByColumn(0, QtCore.Qt.AscendingOrder)
    view.horizontalHeader().setStretchLastSection(True)
    view.horizontalHeader().setSectionsMovable(True)

    view.show()
    app.exec_()

我怀疑我不必将 viewproxy_model 传递给 class,并且我可以通过其他方式访问这些对象。这可能吗?如果可能 - 如何实现?


我知道我的示例是 Python 特定的,但我的问题实际上是一个与绑定无关的问题,所以我也用 qt 标记我的问题。

基本模型不应该知道视图或代理,所以你应该有类似下面的内容:

class MyTableModel(QtCore.QAbstractTableModel):
    def __init__(self, table_data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self.table_data = table_data

    def rowCount(self, parent):
        return len(self.table_data)

    def columnCount(self, parent):
        return len(self.table_data[0])

    def flags(self, index):
        original_flags = super(MyTableModel, self).flags(index)
        return original_flags | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            item = index.internalPointer()
            if item is not None:
                print(item)
            value = self.table_data[row][column]
            return value

    def setData(self, index, value, role=QtCore.Qt.EditRole):
        if role == QtCore.Qt.EditRole:
            row = index.row()
            column = index.column()
            self.table_data[row][column] = value
            self.dataChanged.emit(index, index)
            return True
        return QtCore.QAbstractTableModel.setData(self, index, value, role)

代理有将更改传递给原始模型的方法,因此通常不需要访问基本模型来进行更改,但需要访问相同的代理才能获得订单我实现了一个小部件并使用了dataChanged() 方法,这可能会导致无限循环,因此我们必须阻止其他 dataChanged() 信号,我们使用 blockSignals().

class Widget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        self.view = QtWidgets.QTableView()
        self.setLayout(QtWidgets.QVBoxLayout())
        self.layout().addWidget(self.view)

        table_data = [['one', 'two', 'three'], ['four', 'five', 'six']]
        proxy_model = QtCore.QSortFilterProxyModel()
        model = MyTableModel(table_data=table_data)
        proxy_model.setSourceModel(model)
        proxy_model.setDynamicSortFilter(True)
        self.view.setModel(proxy_model)
        proxy_model.dataChanged.connect(self.on_data_changed)

        self.view.setSortingEnabled(True)  # requires proxy model
        self.view.sortByColumn(0, QtCore.Qt.AscendingOrder)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.horizontalHeader().setSectionsMovable(True)

    def on_data_changed(self, _from, _to):
        model = _from.model() # proxy model
        model.blockSignals(True)
        for index in self.view.selectionModel().selectedIndexes():
            model.setData(index, _from.data())
        model.blockSignals(False)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

更新:

似乎 PySide2 有一个错误,因为它没有 return 选定的元素,而是一个空列表,因此它不会进入 for 循环,在我们为它创建该列表之前,我们使用selectionModel()selectionChanged 信号,这在 PyQt5 中不会发生。:

class Widget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        [...]
        self.view.horizontalHeader().setSectionsMovable(True)

        self.view.selectionModel().selectionChanged.connect(self.on_selectionChanged)
        self.currentSelected = []

    def on_selectionChanged(self, selected, deselected):
        for ix in selected.indexes():
           if ix not in self.currentSelected:
            self.currentSelected.append(ix)
        for ix in deselected.indexes():
            if ix in self.currentSelected:
                self.currentSelected.remove(ix)

    def on_data_changed(self, _from, _to):
        model = _from.model() # proxy model
        model.blockSignals(True)
        pindexes = [QtCore.QPersistentModelIndex(ix) for ix in self.currentSelected]
        for index in pindexes:
            model.setData(index, _from.data())
        model.blockSignals(False)