pyqt button automatically binds to on_…_clicked function without connect or pyqtSlot

不想你离开。 提交于 2019-12-01 12:09:04

Why this auto connect?

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

C++:

void on_<object name>_<signal name>(<signal parameters>);

Python:

def on_<object name>_<signal name>(<signal parameters>):

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!