Qabstratcttablemodel - Removerows
Solution 1:
The problem is caused because you have set the value of the row when you have created each delegate, so its value is not updated.
A possible solution is to use a lambda function to pass a QPersistenModelIndex
associated with the temporary QModelIndex
, but I have seen that there is an unexpected behavior that is creating a selection, so I called clearSelection()
.
It is not necessary to connect to the cellButtonClicked slot since you can directly access the model using QModelIndex or QPersistenModelIndex.
class ButtonDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
btn = QPushButton("X")
ix = QPersistentModelIndex(index)
btn.clicked.connect(lambda ix = ix : self.onClicked(ix))
layout.addWidget(btn)
layout.setContentsMargins(2,2,2,2)
if not self.parent().indexWidget(index):
self.parent().setIndexWidget(index, widget)
def onClicked(self, ix):
model = ix.model()
model.removeRow(ix.row())
self.parent().clearSelection()
Another option is to handle the clicked events through editorEvent
since the provided QModelIndex
has updated values as shown below:
classButtonDelegate(QStyledItemDelegate):
def__init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.state = QStyle.State_Enabled
defpaint(self, painter, option, index):
button = QStyleOptionButton()
button.rect = self.adjustRect(option.rect)
button.text = "X"
button.state = self.state
QApplication.style().drawControl(QStyle.CE_PushButton, button, painter)
defeditorEvent(self, event, model, option, index):
if event.type() == QEvent.Type.MouseButtonPress:
self.state = QStyle.State_On
returnTrueelif event.type() == QEvent.Type.MouseButtonRelease:
r = self.adjustRect(option.rect)
if r.contains(event.pos()):
model.removeRow(index.row())
self.state = QStyle.State_Enabled
returnTrue @staticmethoddefadjustRect(rect):
r = QRect(rect)
margin = QPoint(2, 2)
r.translate(margin)
r.setSize(r.size()-2*QSize(margin.x(), margin.y()))
return r
In addition to this it is not necessary to iterate through data(), we can delete the row directly:
defremoveRow(self, row, parent=QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.cycles.remove(self.cycles[row])
self.endRemoveRows()
self.getData()
In the following link both options are implemented.
Post a Comment for "Qabstratcttablemodel - Removerows"