I have a QStandardItemModel where each item manages a database entity, so every row has one column and the rows adjust matching to the database events. Now I want to generate a table from one subtree of this model, not a list. Therefore, every item will be asked for two different values and a proxy model will display them as two cells of a row. I don't want to change the standard item model. I want to have a proxy model that displays to values per item in separate columns. The standard item model has only one column.
When I created the model the first column got displayed as expected, but the second one was neither selectable nor enabled and all cells of the column were empty. Below you'll find my MWE for reproduction.
I tried generating different indices for the columns but The data() method only gets called for indices with column=0, so the problem is not about roles where I shouldn't return None or other stuff. Even flags() are ignored for the second column.
I expected a two columned table with my data displayed based on the items my model holds.
In my MWE I don't use the item's original text, but return a dummy text for all items that definetly can be calculated and is identifying.
What I get is this table with a phantom like second column:
| 0 | 1 |
|---|---|
| 0-0 | |
| 1-0 | |
| 2-0 |
Why is this happening and how can I add my column with extra data?
import sys
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex, Qt, QIdentityProxyModel
from PyQt5.QtGui import QStandardItem, QStandardItemModel
VARIANT = 2 # 1 or 2
class AddProxyModel(QSortFilterProxyModel):
def columnCount(self, parent: QModelIndex = ...) -> int:
return 2
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):
if role == Qt.DisplayRole:
return str(section)
return super(AddProxyModel, self).headerData(section, orientation, role)
def data(self, index: QModelIndex, role: int = ...):
if index.column() != 0:
print("Called for something != 0")
if role == Qt.DisplayRole:
return f"{index.row()}-{index.column()}"
new_index = self.index(index.row(), 0, index.parent())
return super(AddProxyModel, self).data(
index if VARIANT == 1 else new_index,
role
)
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
if __name__ == "__main__":
app = QApplication(sys.argv)
model = QStandardItemModel()
model.appendRow(QStandardItem("A"))
model.appendRow(QStandardItem("B"))
model.appendRow(QStandardItem("C"))
# p = QIdentityProxyModel()
# p.setSourceModel(model)
proxy = AddProxyModel()
# proxy.setSourceModel(p) # also not working
proxy.setSourceModel(model)
table = QTableView()
table.setModel(proxy)
table.show()
sys.exit(app.exec_())