I have a custom QAbstractItemModel
class QJsonTreeModel(QAbstractItemModel):
With this removeRows() method
def removeRows(self, position, rows, parent):
parentItem = self.getItem(parent)
self.beginRemoveRows(parent, position, position + rows - 1)
parentItem.removeChildren(position, rows)
self.endRemoveRows()
self.layoutChanged.emit()
Where removeChildren() is from
class QJsonTreeItem(object):
def __init__(self, data, parent=None):
self._parent = parent
self._key = ""
self._value = ""
self._type = None
self._children = list()
self.itemData = data
...
def getItem(self, index):
if not index.isValid():
item = index.internalPointer()
if item:
return item
return self._rootItem
def removeChildren(self, position, rows):
if position < 0 or position + rows > len(self._children):
return False
for row in range(rows):
self._children.pop(position)
return True
In my main window class I have right click QMenu() with a couple of methods including delete row method which looks like it:
actionDel = rightClickMenu.addAction(self.tr("Delete Item"))
actionDel.triggered.connect(partial(self.treeItemDelete))
...
def treeItemDelete(self):
index = self.treeView.selectionModel().currentIndex()
parent = index.parent()
parentItem = self.model.getItem(parent)
self.model.removeRows(position=index.row(), rows=1, parent=parent)
It works correctly for root items, for example if I would like to delete "coa" element he will remove it Correclty working example
But if I would like to delete element "index" it would remove element "asd" Not working
Can someone help me to fix this problem?
So as I mentioned in the comment the problem was in getItem(self, index)
function. Somehow I wrote the wrong if
statent. @musicamante is right, if the problem is in getItem() function, I need to fix exactly this function, not an unrelated function.
The working code for me is below:
def getItem(self, index):
if index.isValid():
item = index.internalPointer()
if item:
return item
return self._rootItem
And the removeRows() is this:
def removeRows(self, position, rows, parent):
parentItem = self.getItem(parent)
self.beginRemoveRows(parent, position, position + rows - 1)
success = parentItem.removeChildren(position, rows)
self.endRemoveRows()
return success
Now it removes correctly node and subnodes items.