尝试复制 MyClass(QObject) 在 Python 中引发 RuntimeError

Attempting to copy MyClass(QObject) throws a RuntimeError in Python

我正在开发 PyQt5 应用程序并试图理解为什么我不能在继承自 [=15] 的 class 上使用 copy.copy =] 这是我的 Switcher class 的 header:

class Switcher(QObject):
    def __init__(self):
        QObject.__init__(self)
        self.modified = True
        self.integer_sliders = []
        self.float_sliders = []
        self.checkboxes = []
        self.drop_downs = []
(...)

我需要创建两个 Switcher class 的副本,为此我使用 copy:

switch = Switcher()
new_switch = copy.copy(switch)

但是这会引发 RuntimeError:

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

为什么会这样,是否可以复制 Switcher object?

copy 所能做的就是为 C++ 对象创建 python 包装器 的浅表副本。这是因为它是一个 python 函数,因此对包装器下的 Qt 对象一无所知。

但是即使它确实知道底层对象,仍然没有办法复制它,因为Qt没有为QObject提供复制构造函数.所以你的要求根本没有意义。

无论如何,我猜您实际上不需要复制 QObject 本身。您真正需要做的是复制它的某些 数据属性 - 为此,您可以轻松编写自己的方法。