【发布时间】:2018-03-26 14:48:45
【问题描述】:
我在一个项目中使用了 PyQt5,并且有以下 sn-p(button 是一个 QPushButton)
def on_receive(self, query):
print("receiving", query)
datapackages = json.loads(query)
for button, datapackage in zip(self.buttonArray, datapackages):
self.wire_up_button(datapackage, button)
def wire_up_button(self, datapackage, button):
title, songid = datapackage["title"], datapackage["songid"]
button.setText(title + " (" + str(datapackage["votes"]) + ")")
button.clicked.connect(lambda: self.upvote(songid))
def upvote(self, sid):
text = '{"action":"upvote", "value":"' + sid + '"}\n'
print(text)
self.send(text)
def send(self, text):
print("Sending")
on_receive 函数连接到一个 soccet 客户端,并在收到数据包时调用。布局有点复杂,因为我的 UI 有很多按钮,迭代它们比硬编码每个按钮更方便。
每当我单击按钮时,连接函数会将按钮连接到 upvote 函数,该函数会创建一个 json 协议并将其发送到套接字服务器。但是,每次点击都会调用wireup-function 两次。 (由于调试打印命令,我确信这一点)。我的程序中的发送函数中没有其他调用。
我推测这可能是由于 clicked.connect 的工作原理(可能在单击 和 释放时触发)。
我使用 QtDesigner 创建 UI,并在我的 main.py 中加载了 .uic
【问题讨论】:
-
拜托,您能否添加更多上下文,例如
connect信号线的位置?通过看到songid,它似乎在一个函数中 -
@PRMoureu 我已经这样做了,它可能会混淆那里发生的事情。我尽我所能使它尽可能可读...
-
是否使用相同的 sid 调用 upvote()?你确定你不会为同一个按钮调用两次wire_up_button吗?
-
它可以在
wire_up_button内使用try: button.clicked.disconnect() except Exception: pass(在.clicked.connect 之前)吗?
标签: python pyqt5 qt-designer qpushbutton