How to update QTableView on QAbstractTableModel Change

12,523

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.

Share:
12,523
alphanumeric
Author by

alphanumeric

Updated on June 14, 2022

Comments

  • alphanumeric
    alphanumeric almost 2 years

    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?

    • PRMoureu
      PRMoureu over 6 years
      you mean a change different from inserting row/column ?
    • alphanumeric
      alphanumeric over 6 years
      Exactly. Example: changing the number of columns returned by QAbstractTableModel's columnCount() method won't update the QTableView.
    • PRMoureu
      PRMoureu over 6 years
      are you already using insertRows() with beginInsertRows() and endInsertRows() ? otherwise you may try the dataChanged event
    • alphanumeric
      alphanumeric over 6 years
      What is the syntax for dataChanged? Please post an example as the answer so we could up vote it!
  • NL23codes
    NL23codes almost 5 years
    Neither of these methods work. dataChanged has no attribute 'connect' and you can't attach an emit to it.
  • PRMoureu
    PRMoureu almost 5 years
    @NLee23 please could you submit a new question with your code ?