添加没有布局的自定义小部件?

Adding custom widget without layout?

我子class编辑了一个小部件 (MyButton) 并给了它我的样式表、动画等

在另一个 class (MyForm) 中,我想使用那个按钮但没有布局。

class MyButton(QPushButton):
    def __init__(self):
        super(MyButton, self).__init__()
        .
        .


class MyForm(QDialog):
    def __init__(self):
        super(MyForm, self).__init__()
        self.btn=MyButton(self)
        self.btn.move(220, 30)

如果我尝试说 self.btn=MyButton(self) 然后 self.btn.move() 出现此错误:

self.btn=MyButton(self)
TypeError: __init__() takes 1 positional argument but 2 were given

我该怎么办?

MyButton class 的 __init__ 函数只有一个参数 - self,指向新创建的 MyButton 实例的指针。但是你给它两个参数 - self,每个方法都将其作为第一个参数接收,以及 parent。 可能的解决方案是:

class MyButton(QtGui.QPushButton):
    def __init__(self, parent):
        super(MyButton, self).__init__(parent)

不过,这并不方便,因为您必须指定 superclass' 参数的整个(可能很长)列表,包括位置参数和命名参数。在这种情况下,Python stars (*, **) 是你最好的朋友:

class MyButton(QtGui.QPushButton):
    def __init__(self, *args, **kwargs):
        super(MyButton, self).__init__(*args, **kwargs)