我曾多次遇到这个问题,动态创建对象,无论它们是用QML还是C++创建的.在仍在使用时删除对象,导致硬崩溃,没有明显原因.这些对象仍然被引用并且是其他对象的一部分,一直到根对象,所以我发现QML在它们的引用数仍然高于零时删除这些对象是很奇怪的.
到目前为止,我找到的唯一解决方案是使用C++创建对象并将所有权明确设置为CPP,从而无法从QML中删除对象.
起初我认为它可能是一个父母问题,因为我使用QObject派生类,动态实例化的QML方法传递Item一个父类,而QtObject甚至没有父属性 - 它没有公开QObject.
但后来我尝试了一个Qobject派生的暴露和使用育儿,最后甚至尝试使用Item只是为了确保对象是正确的父对象,但这种行为仍然存在.
这是一个产生这种行为的例子,遗憾的是我无法将其压平为单个源,因为Components 的深层嵌套会破坏它:
// ObjMain.qml
Item {
property ListModel list : ListModel { }
Component.onCompleted: console.log("created " + this + " with parent " + parent)
Component.onDestruction: console.log("deleted " + this)
}
// Uimain.qml
Item {
id: main
width: childrenRect.width
height: childrenRect.height
property Item object
property bool expanded : true
Loader {
id: li
x: 50
y: 50
active: expanded && …Run Code Online (Sandbox Code Playgroud)