1 回答
TA贡献1783条经验 获得超4个赞
当您创建一个对象并为其分配相同的变量时,前一个对象被销毁,可以通过以下测试观察到:
class Foo:
def __del__(self):
print("destroyed")
print("before creating Foo object: 1")
foo = Foo()
print("after creating Foo object: 1")
print("before creating Foo object: 2")
foo = Foo()
print("after creating Foo object: 2")
输出
before creating Foo object: 1
after creating Foo object: 1
before creating Foo object: 2
destroyed
after creating Foo object: 2
destroyed
正如您所看到的,当第二个对象被分配给同一个变量时,第一个销毁被调用。所以这不是 PySide2 的魔力而是 python 的魔力,同样可以用被破坏的信号来验证。
from PySide2.QtCore import QObject
print("before creating QObject object: 1")
qobject = QObject()
qobject.destroyed.connect(lambda _id=id(qobject): print("destroyed1: ", _id))
print("after creating QObject object: 1")
print("before creating QObject object: 2")
qobject = QObject()
qobject.destroyed.connect(lambda _id=id(qobject): print("destroyed2: ", _id))
print("after creating QObject object: 2")
输出:
before creating QObject object: 1
after creating QObject object: 1
before creating QObject object: 2
destroyed1: <PySide2.QtCore.QObject(0x562c1b6ee2f0) at 0x7f4a1faece40>
after creating QObject object: 2
如果你不希望这个问题发生,那么使用 Qt 的超能力,你可以将对象作为“qmap”的父对象传递,这样所有权将由 QObject 持有,它将不再由 python 处理:
from PySide2.QtCore import QObject
from PySide2.QtQml import QQmlPropertyMap
qmap = QQmlPropertyMap()
obj = QObject(qmap)
qmap.insert("test_key", obj)
obj = QObject(qmap)
qmap.insert("test_key2", obj)
print(qmap.value("test_key"))
print(qmap.value("test_key2"))
输出:
<PySide2.QtCore.QObject(0x559629d1e230) at 0x7fef951f01c0>
<PySide2.QtCore.QObject(0x559629d1eae0) at 0x7fef951f0240>
更新:
为了更好地理解,我们必须知道PySide2(PyQt5也适用)的QObject是Qt的QObject的包装器,也就是说,它是这样的:
class PyQObject:
def __init__(self, *args):
self._qobject_cpp = CPPQObject(*args)
# ...
def __del__(self):
delete self._qobject_cpp
添加回答
举报