是否可以查询 PyQt4 QObject 以确定底层 C++实例已被破坏?

发布于 2024-10-19 04:43:18 字数 182 浏览 1 评论 0原文

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

The destroyed() signal can be trapped for a QObject, but I would like to simply test if the Python object still references a valid C++ Qt object. Is there a method for doing so directly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

计㈡愣 2024-10-26 04:43:18

如果导入 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

If you import the sip module you can call its .isdeleted function.

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
思念满溢 2024-10-26 04:43:18

您可以使用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.')

You can use the WeakRef class in the Python standard library. It would look something like:

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.')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文