PyQt and QSignalMapper/lambdas - multiple signals,

2019-02-20 18:49发布

问题:

I have a list of actions on a menu in PyQt, one for each different feed I want to display. So I have a Y that sets the active feed to Y, Z sets it to Z, etc. (For a webcomic reading program).

I have each on the menu, and felt that an automated approach might be better; rather than typing out each time. Something like a function that adds it to a dictionary, then connects it up with a signal for each to a single slot.

However, I want that slot function, say it's called Foo, to take a parameter to decide what has been clicked. So if X was clicked, then X, Y passes Y, etc.

Looked around, and one SO question said to use a lambda, which didn't look...right somehow.

The other way was with QSignalMapper. I tried looking for this, but couldn't find an example of how to use it.

Can anyone help?

Thanks!

回答1:

You can use functools.partial (link to the documentation):

import functools
...

# note that these are the 'new style' slot connections (not necessarily needed)
self.menu_entry_x.triggered.connect(functools.partial(myfunc, x))
self.menu_entry_y.triggered.connect(functools.partial(myfunc, y))

The example is above is very basic, but I could elaborate if you have more questions.