[PyQt] multiple signal connect

David Boddie david at boddie.org.uk
Wed Aug 20 22:35:25 BST 2008


On Wed, 20 Aug 2008 16:17:29 +0100, Ruben Fonseca wrote:

> I have a bunch of buttons that I want to watch for the "clicked()"
> signal.

[...]

> However, every time I click on a button I got on the console
>
> "Received a signal from button_0"
>
> regardless the button I click... So I'm guessing something's wrong with
> my lambda function.

That may be possible. However, there are a couple of alternative ways to
do this.

> What's the best way of solving this particular problem in Python?

One classic Qt way is to just connect the signal for each button to the same
slot. Then, you call your widget's self.sender() method to find out which
one sent the signal.

Another way is to use QSignalMapper to create a mapping between buttons and
values that can be used in the slot to check which button was clicked.
You register each button with the mapper, assigning it a value, then connect
it's clicked() signal to the mapper's map() slot:

  mapper = QSignalMapper(self)

  for button in buttons:
      mapper.setMapping(button, button.objectName())
      self.connect(button, SIGNAL("clicked()"), mapper, SLOT("map()"))

Then you connect the mapper's mapped() signal to the slot in your widget:

  self.connect(mapper, SIGNAL("mapped(QString)"), self.button_clicked)

http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qsignalmapper.html

David


More information about the PyQt mailing list