Frage

I have an editable QTreeWidget and wish to update some internal structures every time the user edits an item. However, there's no signal emitted specifically when some item is changed. There is itemChanged(), but it's emitted not only when the item is changed, but when it is created as well. So far I can't find an elegant way to distinguish between the two cases.

The only solution I invented was something like this:

# slot for itemClicked()
def EditName(self, item, column):
    self.oldname = item.text(0)

# slot for itemChanged()
def RenameFile(self, item, column):
    newname = item.text(0)
    if newname != self.oldname:
        # Do something with newname here

However, it's not very convenient because I'll have to set self.oldname manually any time I add a new item to the tree, which happens in quite a lot of places in the code.

War es hilfreich?

Lösung

One way to track changes would be to create a subclass of QTreeWidgetItem and reimplement its setData function.

The reimplemeted function could then check the role argument to see which action to take:

class TreeWidgetItem(QtGui.QTreeWidgetItem):
    def __init__(self, *args, **kwargs):
        QtGui.QTreeWidgetItem.__init__(self, *args, **kwargs)
        self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)

    def setData(self, column, role, value):
        if role == QtCore.Qt.EditRole:
            # do important stuff here...
            print 'before: "%s", after: "%s"' % (
                self.text(column), value.toString())
        QtGui.QTreeWidgetItem.setData(self, column, role, value)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top