Issue
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?
Solution
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.
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.
Example:
Whenever a new button occurs in your widget
new_button.clicked.connect(self.parent().buttons_clicked)
# always the same recipient
And in the parent class:
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.
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.
Answered By - Trilarion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.