4

I want to understand what is the difference between deleting a widget(include it's layout and children in this layout) using sip.delete() and deleteLater(). I know that removeWidget() and setParent(None) is just removing the widget from layout, but it's not deleting the object itself from the memory. If I want to delete an object from a memory, which one shall I use? I know this question is asked before, but I hope to get detailed answer:)

Zidan
  • 95
  • 1
  • 12

1 Answers1

4

I recommend you read this answer since I will use several concepts explained there.

The sip.delete() is used to directly invoke the destructor of the C++ object from the wrapper, something like:

delete wraper_instance->_cpp_object;

Instead deleteLater() is a method of the QObjects that sends an event so that the eventloop calls the destructor of the C++ object, something like:

  1. post QDeferredDeleteEvent.
  2. Run all pending events.
  3. Destroy the object.
  4. emit the destroyed signal.

Why do QObjects have as an alternative to deleteLater()? Well, directly deleting a QObject can be unsafe, for example let's assume that some QWidget (which is a QObject) is deleted invoking the destructor directly but a moment before in another part of the application it asks to update the entire GUI, as the GUI is not notified removing the object will then cause unallocated memory to be accessed causing the application to crash.

Therefore if you want to delete a QObject then it is safer to use deleteLater(), for other C++ objects (like QImage, QPixmap, QGraphicsItems, etc) you should use sip.delete().

For more information read:

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Lesiok on Qt forum: "Qt::WA_DeleteOnClose setting makes a call to the widget deleteLater" Link: https://www.qtcentre.org/threads/56560-Difference-between-WA_DeleteOnClose-true-and-deleteLater() – Rhdr Jul 16 '20 at 06:48
  • so what's the difference bewtween del and widget.deleteLater() in python? – bactone Nov 26 '21 at 01:26
  • @bactone Read https://stackoverflow.com/questions/6146963/when-is-del-useful-in-python – eyllanesc Nov 26 '21 at 01:29
  • 1
    @bactone deleteLater deletes the C++ object (actually tells the eventloop to delete it when it can, it's an asynchronous C++ delete). The meaning of "del" in python is different from "delete" in C++. – eyllanesc Nov 26 '21 at 01:31
  • @eyllanesc, after some read, I think del x just removes the reference or pointer x, not the object it points to. only if there is is no other references to the object, then it will be garbage collected. deleteLater() seems to remove reference too, am i right? – bactone Nov 26 '21 at 09:05