问题描述
今天我在我们的程序中遇到了奇怪的错误.从 QObject
继承的类的对象正在被类型为 QEvent::DefferedDelete
的事件删除,而没有人可能发送它.
Today I've faced strange bug in our program. The object of a class inherited from QObject
was being deleted by event with type QEvent::DefferedDelete
, while nobody could possibly send it.
它作为 QVariant 传入 QML:
It was passed into QML as QVariant:
// cpp:
Q_INVOKABLE QVariant currentDevice_v() const {
return QVariant::fromValue(_current);
}
// qml:
Component.onCompleted: {
curDevice = devicesModel.currentDevice_v()
#...
}
没有那条 qml 行,一切都运行良好 - 不会产生删除事件.
Without that qml line everything worked well - nothing produces delete event.
推荐答案
我发现如果我在将 QObject
传递给 QML 之前设置它的父级,那么它不会't 被删除.因此,我得出的结论是,将非父级 QObject 传递到 QML 范围会使该范围成为 QObject
的父级,并在范围结束后调用其析构函数.
What I've figured out that if I set the parent of that QObject
before I pass it into QML, then it doesn't get deleted. So, I've concluded that passing unparented QObject into QML scope makes that scope become a parent of QObject
and call its destructor after scope ends.
分享这个,因为我在任何地方都没有找到答案.但是在写这篇文章时,我发现了类似的未解决的问题:Qt5.6 QML,为什么垃圾回收后动态模型会被销毁?
Sharing this out, as I haven't found an answer anywhere. But while writing this post I've found similar unanswered issue: Qt5.6 QML, why are dynamic models destroyed after garbage collection?
这篇关于QObject 在放入 QML 变量后被销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!