我可以有一个插槽用于多个信号吗? [英] Can I have one slot for several signals?

查看:44
本文介绍了我可以有一个插槽用于多个信号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个按钮,每个按钮都有一个信号,每当单击按钮时都会发出它们的一个属性(例如,一个整数).在父类中,我希望能够捕获任何按钮的发射并根据按钮的特定属性做出反应.

I have several buttons, each with a Signal that emits one of their attributes (say, an integer) whenever the button is clicked. In a parent class, I'd like to be able to catch any of the buttons' emits and react based on that particular attribute from the button.

我可以想出一种方法来通过单独连接"父类中的每个按钮来实现这一点,但这似乎是错误且麻烦的,因为在我的应用程序中,我添加和删除按钮作为功能的一部分.我可能想错了...和建议?

I can think of a way to do that by individually 'connecting' each button in the parent class, but that seems wrong, and cumbersome, because in my application I add and remove buttons as part of the functionality. I'm probably thinking about it wrongly... and suggestions?

推荐答案

在 Qt 中,您可以将任何信号连接到任何插槽.这也意味着您可以将单个信号与多个插槽或多个信号与单个插槽连接.

In Qt you can connect any signal with any slot. This also means you can connect a single signal with several slots or several signals with a single slot.

现在,如果每个按钮都做不同的事情并且没有那么多,我会手动将每个按钮与不同的插槽连接起来,以便很好地分开.

Now if every button does a different thing and there aren't that many I would connect each one manually with a different slot just to have things nicely separated.

在您的情况下,您可能希望以自动方式将所有按钮与单个插槽连接起来,并在此插槽中通过 self.sender() 确定原始按钮,然后对此进行处理信息.

In your case you probably want to connect all the buttons with a single slot in an automatic fashion and in this slot determine the button of origin by self.sender() and then do something with this information.

示例:

每当您的小部件中出现新按钮时

Whenever a new button occurs in your widget

new_button.clicked.connect(self.parent().buttons_clicked)
# always the same recipient

在父类中:

def buttons_clicked(self):
  button = self.sender()
  # do something useful depending on the button that sent the signal

这里缺少的是您转移属性(数字或其他)的方式.您现在没有具体说明如何执行此操作,但可能不应通过连接到同一插槽对其进行显着更改.

What is missing here is the way you transfer your attribute (the number or whatever). You didn't specify how you do it now but it should probably not be altered significantly by connecting to the same slot.

作为旁注,Qt 中也有大致相同的事件.信号/插槽与事件是一个有趣的讨论.根据您的问题(许多动态按钮)而不是连接和断开连接,发送事件可能会更好.

edit: As a sidenote, there are also events in Qt which roughly do the same. Signals/slots vs events is an interesting discussion. Depending on your problem (many dynamic buttons) instead of connecting and disconnecting you might be better off with sending events.

这篇关于我可以有一个插槽用于多个信号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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