【问题标题】:Adding custom widget without layout?添加没有布局的自定义小部件?
【发布时间】:2016-01-02 00:35:33
【问题描述】:

我将一个小部件 (MyButton) 子类化,并给它我的样式表、动画等。

在另一个类(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

我该怎么办?

【问题讨论】:

  • 我认为你应该从self.btn=MyButton(self) 中删除自我 ---> self.btn=MyButton()
  • @ Ehsan Abd 在这种情况下 self.btn 在 MyForm.BTW 中不可见,使用标准 QPushButton(self) 很好

标签: qt pyqt pyqt5


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多