Search code examples
pythonqtqt4qt5

How to update QTableView on QAbstractTableModel Change


While working with the QTableView and QAbstractTableModel there are times when the QTableView is not updated with the changes taking place in QAbstractTableModel's data. In order to "enforce" or to trigger the view update I use QAbstractTableModel's self.layoutChanged.emit() method.

While it works I have noticed this method may cause some instability and even a crash. I wonder if there is an alternative way to update the QTableView when the QAbstractTableModel changes?


Solution

  • Basically, you can connect a function to the model dataChanged signal/event, or you can insert this signal inside the function used to modify the model if you have implemented one.

    The first option could be like below, in your model class,

    self.dataChanged.connect(self.view.refresh) 
    

    where refresh() is a custom slot in your view which trigger a simple self.update(), otherwise you need to handle the parameters send by the signal (affected parents QModelIndex).


    The second option needs to emit the signal with QModelIndex, call this in the function when you apply some changes in the model class :

    self.dataChanged.emit(self.index(X, Y), self.index(X, Y)) 
    

    where X and Y represent the position of the changed data in your table

    The third parameter role is an option, i.e. you can specify the DisplayRole, otherwise all roles can be updated.