Python: RuntimeError: super-class __init__() of %S was never called

前端 未结 1 1780
生来不讨喜
生来不讨喜 2020-12-06 16:59

I tried to do some operation (setParent) on an object in Python (an instance of a class which inherits from a different class - to be specific, QtGui.QLab

相关标签:
1条回答
  • 2020-12-06 17:55

    If you want to inherit QObject (or QWidget), you must always call the super-class __init__:

    class MyObject(QObject):
        def __init__(self, *args, **kwargs):
            super(MyObject, self).__init__(arguments to parent class)
            #other stuff here
    

    You may also call the parent's class's __init__ after some instructions, but you can't call QObject methods or use QObject attributes until you did so.


    Edit: In your case you are trying to deepcopy a QWidget, but this is not possible. Python may be able to copy the wrapper of the QWidget, but the QWidget itself is a C++ object that python cannot handle with the default implementation of copy.deepcopy, hence whenever you call a method of the copied instance you get the RuntimeError because the underlying C++ object wasn't initialized properly.

    The same is true for pickling these objects. Python is able to pickle the wrapper, not the C++ object itself, hence when unpickling the instance the result is a corrupted instance.

    In order to support deepcopy() the QWidget class should implement the __deepcopy__ method, but it does not do that.

    If you want to copy widgets you'll have to implement by yourself all the mechanism by hand.

    0 讨论(0)
提交回复
热议问题