PyQt QAbstractTableModel never updates when rows are added
pyqt, python, qt
Solution
There is one issue, which I think is the cause of your problem. It's about line:
self.beginInsertRows(self.createIndex(0, 0), index, index)
`self.createIndex(0, 0)` will create a valid `QModelIndex`. That refers to `parent` in `beginInsertRows`, so you are basically telling the view that you'll be adding a child to the first row in the table. Since the table has no concept of children (it's not hierarchical), it doesn't do anything.
For a table, `parent` should be an invalid `QModelIndex`, meaning your items are at the root. So, you should use:
self.beginInsertRows(QtCore.QModelIndex(), index, index)
# or depending on how you import
self.beginInsertRows(QModelIndex(), index, index)
That being said, there are a couple of things that struck me as odd.
First, outside of the `index` method, you generally should avoid calling `createIndex` directly. Otherwise it's easy to mess things up. `index` method itself should provide a consistent way of creating `QModelIndex` instances. In your case, since you inherit `QAbstractTableModel`, `index` method is already implemented.
Second, you are using global variables. A lot. It's generally considered bad practice. If your class needs them, then pass them to `__init__`. For instance, right now you can't instantiate two independent models. Because they'll both use the same global `figure` variable. Or, I don't know what `EMPTY` refers to but `data` should simply return `None` for invalid types. No need for another name. Similarly you should be able to get `COLUMNS` from `figures` or if you need an explicit value, you should pass that to `__init__`.
Problem
I've got a PyQt `QTableView`, hooked up to a `QAbstractTableModel`, which itself is hooked up to a custom class managing a list of items. I can insert an item on the end of the list, and it appropriately notifies my model, which then calls `beginInsertRows` and `endInsertRows`. I can verify that it calls both those functions, and the list has updated itself, but the table never calls `data` to retrieve the updated rows. What's going on? How can I fix it? ``` class FigureTableModel(QAbstractTableModel): def __init__(self): QAbstractTableModel.__init__(self) def changed(index): start_index = self.createIndex(index, 0) end_index = self.createIndex(index, COLUMNS - 1) self.dataChanged.emit(start_index, end_index) def adding_row(index): self.beginInsertRows(self.createIndex(0, 0), index, index) print 'adding ', index def added_row(index): self.endInsertRows() print 'added' figures.dataChanged.connect(changed) figures.rowAdding.connect(adding_row) figures.rowAdded.connect(added_row) def rowCount(self, parent): return len(figures) def columnCount(self, parent): return COLUMNS def data(self, index, role): print 'in data' if not index.isValid(): return EMPTY return figures[index.row()].get_table_item(index.column(), role) ```