Search code examples
c++qtpointersqitemdelegate

How Qt manage the memory of an Widget pointer which is returned from the function QItemDelegate::createEditor()


I am checking the Qt example Spin Box Delegate example. In the example

QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &/* option */,
    const QModelIndex &/* index */) const
{
    QSpinBox *editor = new QSpinBox(parent);
    ...
    return editor;
}

How is the pointer editor deleted in the later stage? Is the deletion done by QItemDelegate destructor? But the destructor of QItemDelegate is not virtual. Anyone could help me to explain how it works?

I can not put any break-point in QtCreator. The way I understand is every time the virtual function createEditor() is invoked, a new trunk of memory will be allocated and the client code will lose pointer at the end of the function. The Qt document about createEditor() does not explain. But I guess each cell in the tableView will have an editor, is that right?

I am really wondering how Qt delete those QWidget pointers.

Thanks


Solution

  • In this case, the ownership of the editor object is passed to the caller of createEditor(). That's usually the QAbstractItemView instance(s) using the delegate for painting. Whenever they need an editor (e.g. because the user clicked into a cell), they call createEditor() on the delegate, place it and show it. Afterwards the editor instances are managed internally in QAbstractItemView and deleted when not used anymore, or when the QAbstractItemView itself is deleted. One can even customise the deletion (or prevent it) by reimplementing QAbstractItemDelegate::destroyEditor(). That's usually not necessary though.

    This particular case is very specific though, it's not a generic Qt mechanism like parent/child relationships at work, but "manual" code in the QAbstractItemView implementation. Search qtbase/src/widgets/itemviews for "releaseEditor" if you want to see the details.

    Often (but unfortunately not always) the Qt documentation mentions the ownership. E.g. for QAbstractItemView::setModel(), the documentation states:

    The view does not take ownership of the model unless it is the model's parent object because the model may be shared between many different views.

    For QItemDelegate::createEditor() nothing is mentioned. It should say something like "The ownership for the created editor widget is passed to the caller" but also mention destroyEditor().