Nominate our 2022 Qt Champions!

QStyledItemDelegate subclass: weird QLineEdit behavior and memory issues, what am I doing wrong?

  • I have a TreeView in my program, and I have a QStyledItemDelegate subclass for customizing editor behavior. This is its complete listing:

    @CFileListItemDelegate::CFileListItemDelegate(QObject *parent) :

    QWidget CFileListItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const
    QLineEdit * editor = dynamic_cast<QLineEdit
    >(QStyledItemDelegate::createEditor(parent, option, index));
    connect(editor, &QLineEdit::returnPressed, ={
    QMessageBox::warning(nullptr, "Test", "Item edited");
    return editor;

    void CFileListItemDelegate::setModelData(QWidget * /editor/, QAbstractItemModel * /model/, const QModelIndex & /index/) const
    // Doing nothing since I only want to save changes when Enter is pressed

    When I press Enter in the editor, the message box is shown as expected. When I click "OK" in the message box to close it, the program crashes due to access violation. Qt is trying to dispatch a QKeyEvent to some QLineEdit whose this pointer is invalid (not a pointer to an already freed object).
    There are no QLineEdits in my UI except for the editor. Any idea what's going on?

    And a second question. If I connect to editingFinished instead of returnPressed, the crash does not occur but I get 2 message boxes one after another. Why?

  • P. S. regarding my second question: the first time the slot is called because of KeyPressEvent that the editor receives when I press Enter, the second one originates in the FocusOut event. This behavior seems weird.

  • I'll appreciate any ideas on the memory issue.

Log in to reply