How to update QTableView on QAbstractTableModel Change
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.
alphanumeric
Updated on June 14, 2022Comments
-
alphanumeric almost 2 years
While working with the
QTableView
andQAbstractTableModel
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'sself.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?
-
PRMoureu over 6 yearsyou mean a change different from inserting row/column ?
-
alphanumeric over 6 yearsExactly. Example: changing the number of columns returned by QAbstractTableModel's
columnCount()
method won't update the QTableView. -
PRMoureu over 6 yearsare you already using
insertRows()
withbeginInsertRows()
andendInsertRows()
? otherwise you may try the dataChanged event -
alphanumeric over 6 yearsWhat is the syntax for
dataChanged
? Please post an example as the answer so we could up vote it!
-
-
NL23codes almost 5 yearsNeither of these methods work. dataChanged has no attribute 'connect' and you can't attach an emit to it.
-
PRMoureu almost 5 years@NLee23 please could you submit a new question with your code ?