如何防止取消勾选QObject时出现运行时错误?

2024-04-26 22:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试取消pickle QObject(使用Python 2.7、PyQt4或5、pickle或cPickle),将引发以下RuntimeError

RuntimeError: super-class __init__() of type QObject was never called

一个简单的例子:

cPickle.loads(cPickle.dumps(QtCore.QObject(), cPickle.HIGHEST_PROTOCOL))

我知道,通过设计,取消勾选对象不会调用对象的__init__()方法。你知道吗

那么,在本例中,如何确保调用超类__init__()?你知道吗

有人问了一个貌似相似的问题,但没有人回答。你知道吗


Tags: of对象inittypepickleclass例子pyqt4
1条回答
网友
1楼 · 发布于 2024-04-26 22:37:51

基于this answer的一个可能的解决方案可以实现如下(一个稍微复杂一点的示例,带有一个自定义属性):

import cPickle
from PyQt5 import QtCore


class MyQObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(MyQObject, self).__init__(parent)
        # Add some custom attribute
        self.some_attribute = 'something'

    def __setstate__(self, state):
        # Restore attributes
        self.__dict__.update(state)
        # Call the superclass __init__()
        super(MyQObject, self).__init__()

original = MyQObject()
pickle_string = cPickle.dumps(original, cPickle.HIGHEST_PROTOCOL)
restored = cPickle.loads(pickle_string)

如果需要,可以使用setParent()设置父级。你知道吗

相关问题 更多 >