【问题标题】:Create dynamic button in PyQt在 PyQt 中创建动态按钮
【发布时间】:2012-05-24 01:49:30
【问题描述】:

我尝试在 PyQt 类中添加一个函数,但它总是返回一个错误。

# Error: TypeError: connect() slot argument should be a callable or a signal, not 'NoneType' # 
def commander (self, arg):
    exec arg    

def aButton (self, layout, **kwargs):
    name = kwargs.pop("name","Button")
    command = kwargs.pop("command", "" )
    button = QtGui.QPushButton(name)
    button.clicked.connect(self.commander(command))
    layout.addWidget(button)
    return button

可能有人可以帮我解决这个问题:') 谢谢!

【问题讨论】:

    标签: python qt pyqt


    【解决方案1】:

    你需要一个函数:

    button.clicked.connect(lambda: self.commander(command))
    

    注意 lambda 会避免函数调用的评估,所以它只会在点击时调用self.commander(command)

    【讨论】:

    • 你能详细解释一下吗?我的意思是解决方案有效,但我不明白为什么......
    • @SKYnine 如果你跳过lambda,那段特定的代码self.commnader(command) 将在该表达式期间被评估,并且永远不会再被评估。结果(无论是什么)都将传递给connect 方法。使用lambda,您将告诉解释器这是一段稍后要执行的代码(因此它将是一个只有一条语句的函数)。然后将该函数传递给connect 方法。
    【解决方案2】:

    出现在

    button.clicked.connect(self.commander(command))
    

    self.commander(command) 正在返回 None 而不是信号或可调用对象。

    【讨论】:

    • 是的,但我只想在单击按钮时执行一些代码。我不明白我需要返回什么样的价值。 return compile(arg, '', 'exec') 我试试,但它是一样的...
    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 2013-02-08
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多