1

I am stumped. In the code below:

class LineEdit(QtGui.QLineEdit):

def __init__(self, value="", parent=None, commit=None):
    super(LineEdit, self).__init__(parent=parent)
    self.setText("blabla")
    self.commit = commit
    self.editingFinished.connect(self.on_change)
    print self.text()

self.text() is "blabla" but the LineEdit does not show the text and after editing self.text() is "". The editor is created in a QStyledItemDelegate() with createEditor() for a QTreeView().

Can anyone explain to me why this happens and how to fix it?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Lars
  • 1,869
  • 2
  • 14
  • 26

1 Answers1

4

If you're using an item delegate, the initial text shown in the editor will be taken from the model, and any existing text will be overwritten.

To control what happens before and after editing, reimplement the setEdtorData and setModelData methods of the item delegate:

class Delegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        if index.column() < 2:
            return LineEdit(parent)
        return super(Delegate, self).createEditor(parent, option, index)

    def setEditorData(self, editor, index):
        if index.column() == 0:
            editor.setText('blabla')
        elif index.column() == 1:
            editor.setText(index.data().toString())
            # Python 3
            # editor.setText(index.data())
        else:
            super(Delegate, self).setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        if index.column() < 2:
            value = editor.text()
            print(value)
            model.setData(index, value, QtCore.Qt.EditRole)
        else:
            super(Delegate, self).setModelData(editor, model, index)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • clear and solved at least one other problem, sort of unclear in the documentation as well – Lars Jan 13 '15 at 23:06