Skip to content Skip to sidebar Skip to footer

Pyqt Button Automatically Binds To On_..._clicked Function Without Connect Or Pyqtslot

I've been using pyqt5 with qt-designer for some weeks now. I'm used to connect signals to handler functions with connect statements. Yesterday I made a piece of code that also aut

Solution 1:

Why this auto connect?

The loadUi() function internally calls the connectSlotsByName() method that makes an automatic connection if some method has the structure:

C++:

voidon_<objectname>_<signal name>(<signal parameters>);

Python:

def on_<objectname>_<signalname>(<signalparameters>):

In your case, the on_pushButton_clicked method meets that requirement because you have a QWidget(inherited from QObject) pushButton with objectname "pushButton":

<widget class="QPushButton" name="pushButton">

that has a signal called clicked.

Why do you call the same method twice?

The QPushButton has a clicked signal that is overloaded, that is to say that there are several signals with the same name but with different arguments. If the docs are reviewed:

void QAbstractButton::clicked(bool checked = false)

Although it may be complicated to understand the above code is equivalent to:

clicked = pyqtSignal([], [bool])

And this is similar to:

clicked = pyqtSignal()
clicked = pyqtSignal([bool])

So in conclusion QPushButton has 2 clicked signals that will be connected to the on_pushButton_clicked function, so when you press the button both signals will be emitted by calling both the same method so that clicked will be printed 2 times.


The connections do not take into account if the previous signal was connected with the same method, therefore with your manual connection there will be 3 connections (2 of the signal clicked without arguments [1 automatically and another manually] and 1 with the signal clicked with argument) so the method will be called 3 times.

When you use the decorator @pyqtSlot you are indicating the signature (ie the type of arguments), so the connect method will only make the connection with the signal that matches the slot signature, so you do not see the problem anymore since you use the signal no arguments

Post a Comment for "Pyqt Button Automatically Binds To On_..._clicked Function Without Connect Or Pyqtslot"