[PyQt] QPushButton.clicked() methods in PyQt5
Baz Walter
bazwal at ftml.net
Sat Aug 30 02:36:40 BST 2014
On 30/08/14 00:58, David Cortesi wrote:
> Working code in PyQt4, to connect signals from an array of QPushButtons:
>
> for j in range(number_of_buttons):
> self.connect(self.userButtons[j], SIGNAL("clicked()"),
> lambda b=j : self.user_button_click(b) )
>
> This caused the clicked() signal of button j to invoke user_button_click()
> passing the value of j, i.e. the index to the clicked button.
>
> Moving this code to the PyQt5 signal API:
>
> for j in range(number_of_buttons):
> self.user_buttons[j].clicked.connect(
> lambda b=j : self.user_button_click(b)
> )
>
> The result is not as before. The user_button_click() method receives False
> from any button, not an int.
>
> At first I thought -- oh, the signal is defined as "clicked(bool
> checked=False)" and so the checked property value is being passed. Even
> though the button is (by default) not checkable, somehow I am getting the
> clicked(bool) version instead of the clicked() overload.
>
> But on second thought -- how could the signal's parameter get into the
> lambda expression, which made no reference to it?
>
> If that is the case, what would be the modern API's version of
> SIGNAL('clicked()'), i.e. selecting a version of a signal that passes NO
> parameter?
Signals that define a default value will always send that value, no
matter what.
With new-style signals, if you don't specify which overload you want, a
default will be chosen. For the clicked signal, the default is
clicked(bool), so to get the clicked() overload you will have to
explicitly select it. To select an overload with no parameters, use an
empty tuple:
self.user_buttons[j].clicked[()].connect(...
Although this looks a little ugly, it's worth getting into the habit of
always explicitly selecting the overload you want with signals that
define default values, because it can be a very common source of bugs
otherwise. It's only too easy to change the signature of a handler later
on, but then forget to update the signal connection as well.
--
Regards
Baz Walter
More information about the PyQt
mailing list