无法从 Python 循环中创建的按钮发送信号 [英] Unable to send signal from Button created in Python loop

查看:58
本文介绍了无法从 Python 循环中创建的按钮发送信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环中创建一系列按钮.每个按钮都会获得一个 id 号,因为它是文本,当单击按钮时,它应该将 id 号发送到将打开存档订单的函数.这时候我只想打印订单号,证明信号有效,每个按键都连接到正确的订单号.

I am trying to create a series of buttons in a loop. Each button gets an id number as it's text and when the button is clicked it is supposed to send the id number to a function that will open an archived order. At this time I just want to print the order number to prove that the signal works and each button is connected to the correct order number.

ui.cmdOpen = QtWidgets.QPushButton(ui.frOrdHist)
ui.cmdOpen.setGeometry(QtCore.QRect(269, line1Y, 61, 22))
ui.cmdOpen.setText(iOrderId)
ui.cmdOpen.setObjectName("cmdOpen")
ui.cmdOpen.clicked.connect(lambda button=ui.cmdOpen:displayOrder(ui, button))


def displayOrder(ui, button):
    i = button.text()
    print(i)

当我单击按钮时,我收到一条错误消息,指出布尔对象没有文本属性"

When I click the button, I get an error message that says "boolean object has no text attribute"

我尝试直接传递订单号,它会打印False",所以仍然是一个布尔值.我不知道布尔值是从哪里来的,一定是信号有问题.

I tried passing the order number directly and it would print "False" so still a boolean. I don't know where the boolean is coming from, it must be something wrong in the signal.

推荐答案

点击信号总是发送按钮的checked状态.因此,这将使用布尔值覆盖您的默认 button 参数,这就是您得到 AttributeError 的原因(即因为 bool 没有该方法).你应该像这样建立连接:

The clicked signal always sends the checked state of the button. So this will overwrite your default button argument with a boolean value, which is why you get the AttributeError (i.e. because bool doesn't have that method). You should instead make the connection like this:

ui.cmdOpen.clicked.connect(
    lambda checked, button=ui.cmdOpen: displayOrder(ui, button))


PS:此问题的另一个常见来源是触发信号 QAction.如果你发现你的槽接收到意外的输入,检查 Qt 文档总是值得的,看看信号的签名是否有任何带有默认值的参数 - 即看起来像这样:


PS: another common source of this issue is the triggered signal of QAction. If you ever find your slots receiving unexpected inputs, it's always worth checking the Qt Docs to see if the signature of the signal has any parameters with default values - i.e. that look something like this:

void QSomeClass::someSignal(bool param = false)

这篇关于无法从 Python 循环中创建的按钮发送信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆