Pyqt5 deleteLater() VS sip.delete()
我想了解使用 sip.delete()
和 deleteLater()
删除小部件(包括它的布局和此布局中的子项)有什么区别.我知道 removeWidget()
和 setParent(None)
只是从布局中删除小部件,但它不会从内存中删除对象本身.如果我想从内存中删除一个对象,我应该使用哪个?我知道之前有人问过这个问题,但我希望得到详细的答案:)
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:)
我推荐你阅读这个答案因为我将使用那里解释的几个概念.
I recommend you read this answer since I will use several concepts explained there.
sip.delete()
用于直接从包装器中调用C++对象的析构函数,例如:
The sip.delete()
is used to directly invoke the destructor of the C++ object from the wrapper, something like:
delete wraper_instance->_cpp_object;
改为deleteLater()
是 QObject
s 的一种方法,它发送一个事件,以便 eventloop 调用 C++ 对象的析构函数,例如:
Instead deleteLater()
is a method of the QObject
s that sends an event so that the eventloop calls the destructor of the C++ object, something like:
- 发布 QDeferredDeleteEvent.
- 运行所有待处理的事件.
- 摧毁物体.
- 发出被破坏的信号.
为什么 QObjects 可以替代 deleteLater()
? 好吧,直接删除一个 QObject 可能是不安全的,例如让我们假设某个 QWidget(它是一个 QObject)被直接调用析构函数删除,但在另一个之前调用析构函数它要求更新整个 GUI 的应用程序的一部分,因为没有通知 GUI 移除对象会导致未分配的内存被访问,从而导致应用程序崩溃.
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.
因此,如果您想删除 QObject
,那么使用 deleteLater()
会更安全,对于其他 C++ 对象(如 QImage、QPixmap、QGraphicsItems 等),您应该使用 sip.delete()
.
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: