Python:RuntimeError:从未调用%S的超类__init __()

Tom*_*mer 10 python runtime-error pyqt deep-copy superclass

我试图对setParentPython中的一个对象(一个继承自不同类的类的实例 - 具体而言QtGui.QLabel)执行一些操作(),但是在运行时期间引发了上述错误.对象本身有一些具有实际内容的字段(在调试时验证),但由于某种原因我无法"使用"它.错误意味着什么,我该如何解决?对于一些其他信息,我会说在我尝试对它执行此操作之前,该对象是从静态方法返回的.

子类具有__init__()自己的功能:

def __init__(self, image, father):
        super(AtomicFactory.Image, self).__init__(father)
        self.raw_attributes = image.attributes
        self.attributes = {}
        father.addChild(self)
        self.update()
Run Code Online (Sandbox Code Playgroud)

现在我写了一个类似的代码,一个简单的代码,widget.setParent(mw)当窗口移动时在行上有相同的错误.

#!/usr/bin/env python
import sys
import copy
from PyQt4 import QtCore, QtGui

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main_widget=QtGui.QWidget()
    widget = QtGui.QPushButton('Test')
    widget.resize(640, 480)
    widget.setParent(main_widget)
    widget.move(0, 0)
    widget2=QtGui.QPushButton('Test2')
    widget2.i=0
    widget2.resize(600, 200)
    widget2.setParent(main_widget)
    widget2.move(640, 0)
    def onResize(event):
        print event
        mw=copy.deepcopy(main_widget)
        widget.setParent(mw)
        widget2.setParent(mw)
        widget.move(0, 0)
        widget2.move(640, 480)
        main_widget_width=main_widget.width()
        widget_width=widget.width()
        width2=main_widget_width-widget_width
        height2=widget2.height()
        widget2.resize(width2, height2)
        widget2.move(640, 0)
    main_widget.resizeEvent=onResize
    def onClick():
        size=(widget2.width(), widget2.height())
        if(widget2.i%2==0):
            widget2.resize(int(size[0]/2), int(size[1]/2))
        else:
            widget2.resize(size[0]*2, size[1]*2)
        widget2.i+=1
    QtCore.QObject.connect(widget, QtCore.SIGNAL('clicked()'), onClick)
    main_widget.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

出了什么问题?

Bak*_*riu 19

如果要继承QObject(或QWidget),则必须始终调用超类__init__:

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

你也可以__init__在一些指令之后调用父类的类,但是在你这样做之前你不能调用QObject方法或使用QObject属性.


编辑:在你的情况你想deepcopy一个QWidget,但是这并不可能.Python的可能是能够复制的包装QWidget,但QWidget本身是一个C++对象是Python不能用的默认实现处理copy.deepcopy,因此只要您拨打复制的实例的方法,你得到的RuntimeError,因为底层的C++对象未初始化正常.

酸洗这些物体也是如此.Python能够腌制包装器,而不是C++对象本身,因此当取消对实例的修改时,结果是一个损坏的实例.

为了支持deepcopy()QWidget类应实现__deepcopy__的方法,但它并没有做到这一点.

如果你想复制小部件,你必须亲自实现所有机制.