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

后端 未结 1 1649
北海茫月
北海茫月 2021-01-17 01:43

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 c

相关标签:
1条回答
  • 2021-01-17 02:11

    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

    0 讨论(0)
提交回复
热议问题