How To Sync Multiple Views Sharing Same Model
A left-side-list-view click populates a right-side-table-view with the corresponding to a clicked item items. The problem is that a right-side-table-view items list keeps growing w
Solution 1:
Now with single row. This row could be hidden when nothing has been selected yet - I just show it as empty.
classTableModel(QtCore.QAbstractTableModel):
sel = Nonedef__init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.items=[]
defrowCount(self, parent=QtCore.QModelIndex()):
return1defcolumnCount(self, index=QtCore.QModelIndex()):
return4defdata(self, index, role):
ifnot index.isValid() ornot (0<=index.row()<len(self.items)): return
key=self.sel
column=index.column()
if role==QtCore.Qt.DisplayRole:
ifnot column: returnstr(key)
else:
return elements.get(key,{}).get(column) if (self.sel isnotNone) else QtCore.QVariant()
defrebuildItems(self, index):
key=index.data(QtCore.Qt.UserRole)
ifnot key in self.items:
self.items.append(key)
self.sel = key
self.dataChanged.emit(self.index(1,1), self.index(1,4) )
classWindow(QtGui.QWidget):
def__init__(self):
super(Window, self).__init__()
mainLayout=QtGui.QHBoxLayout()
self.setLayout(mainLayout)
self.dataModel=ListModel()
self.dataModel.buildItems()
self.dataModelB=TableModel()
self.viewA=QtGui.QListView()
self.viewA.setModel(self.dataModel)
self.viewA.clicked.connect(self.onClick)
self.viewB=QtGui.QTableView()
self.viewB.setModel(self.dataModelB)
mainLayout.addWidget(self.viewA)
mainLayout.addWidget(self.viewB)
self.show()
defonClick(self, index):
self.viewB.model().rebuildItems(index)
Solution 2:
This does what you asked, as far as not repeating insertions:
defrebuildItems(self, index):
key=index.data(QtCore.Qt.UserRole)
totalItems=self.rowCount()
ifnot key inself.items:self.beginInsertRows(QtCore.QModelIndex(), totalItems, totalItems)
self.items.append(key)
self.endInsertRows()
However, for hiding items, that is something done by the view (or a proxy model), not the model itself.
Post a Comment for "How To Sync Multiple Views Sharing Same Model"