【问题标题】:Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?是否可以查询 PyQt4 QObject 以确定底层 C++ 实例是否已被销毁?
【发布时间】:2011-02-25 20:48:14
【问题描述】:

destroyed() 信号可以为 QObject 捕获,但我想简单地测试 Python 对象是否仍然引用有效的 C++ Qt 对象。有没有直接这样做的方法?

【问题讨论】:

  • 在 C++ Qt 中没有比捕捉destroyed() 信号更简单的可能性了,所以我怀疑这在 PyQt 中是否可行。

标签: python qt pyqt pyqt4


【解决方案1】:

如果你导入 sip 模块,你可以调用它的 .isdeleted 函数。

import sip
from PyQt4.QtCore import QObject

q = QObject()
sip.isdeleted(q)
False

sip.delete(q)
q
<PyQt4.QtCore.QObject object at 0x017CCA98>

q.isdeleted(q)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: underlying C/C++ object has been deleted

【讨论】:

  • 没有sip(或shiboken)可以吗?
  • 我发现在某些情况下从 PyQt 导入 sip 效果更好。以from PyQt5 import sip 完成。
【解决方案2】:

您可以使用 Python 标准库中的 WeakRef 类。它看起来像:

import weakref

q = QObject()
w = weakref.ref(q)

if w() is not None: # Remember the parentheses!
    print('The QObject is still alive.')
else:
    print('Looks like the QObject died.')

【讨论】:

  • 问题是关于 Qt 对象,而不是 Python 对象。即使这可能只是偶然发生,但这不是做到这一点的方法。而且这比听信号更费力。
  • @Rush:他问“我想简单地测试一下 Python 引用是否仍然有效”。所以这正是它的作用。
  • 对不起,那句话不清楚。我在问底层的 C++ 对象。我会解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多