How to update QAbstractTableModel and QTableView after sorting a data source?

I have a custom data structure that I want to display in a PyQt application using QTableView. I am using a subclass of QAbstractTableModel to communicate with the data. The data structure itself is in a separate module and does not know anything about PyQt.

Displaying and editing data using QTableView works, but now I want to sort the data and then update the model and view.

After reading the Qt documentation for QAbstractTableModel and its ancestor QAbstractItemModel, my first approach was to try the following:

class MyModel(QtCore.QAbstractTableModel):
    __init__(self, data_structure):
        super().__init__()
        self.data_structure = data_structure

    # ...

    def sort_function(self):
        self.layoutAboutToBeChanged.emit()
        # custom_sort() is built into the data structure
        self.data_structure.custom_sort()
        self.layoutChanged.emit()

However, this does not allow updating the view. I also tried to emit a DataChanged signal in all the data used by the model, but this also failed to update.

. , , QPersistentModelIndexes , .

? , (, , )?

+4
2

custom_sort() . .

class MyModel(QtCore.QAbstractTableModel):
    __init__(self, data_structure):
        super().__init__()
        self.data_structure = data_structure

    # ...

    def sort_function(self):
        self.layoutAboutToBeChanged.emit()
        # custom_sort() is built into the data structure
        self.data_structure.custom_sort()
        self.layoutChanged.emit()
+4

.

def ImportFile(self):
    fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File", "", "CSV Files (*.csv)")
    self.table_model.layoutAboutToBeChanged.emit()
    self.DealDf(fileName)
    self.table_model.layoutChanged.emit()

DataFrame, DealDf DataFrame, , ? ?

def data(self, index, role):

    i = index.row()
    j = index.column()
    value = self.df_.ix[i, j]
    if role == QtCore.Qt.DisplayRole:
        if type(value) is float and np.isnan(value):
            return ''
        else:
            return '{0}'.format(value)
0

All Articles