Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Detect if a button has been pressed (100 buttons)



  • My software have 100 buttons, how to detect if a button has been pressed (without create 100 functions)?

    af58c822-7e54-468e-bb48-ad9dad2e9da8-image.png



  • @Black-Cat
    When a button is pressed it raises a signal. You connect the signal to a slot. Normally the signal does not convey any information about which button has been pressed, and for different buttons you connect to different slots, so you don't need to know which button was pressed. As you say, that would lead to having to declare 100 distinct button slot functions.

    You should instead use a Python lambda as the slot for the signal. Via that you can pass a parameter through the signal to a single slot to identify which button has called it.

    I assume your 100 buttons are stored in a Python array. (If not, you will need to do something like this, or you will have to use QObject.findChildren() to visit each button.) You will then need something like:

    for i in range(len(self.buttonArray)):
        btn = self.buttonArray[i]
        btn.clicked.connect(lambda i : self.onButtonClicked(i))
        # line above may not be right because of the `checked` argument passed by the `clicked` signal
        # you may instead need:
        btn.clicked.connect(lambda checked, i : self.onButtonClicked(i))
        # or even:
        btn.clicked.connect(lambda checked, x=i : self.onButtonClicked(x))
    
    def onButtonClicked(i):
        print(i)
    


  • @JonB

    I having try this but every time is printing the same number?! I

            for i in range(len(host_array)):
                exec(f"global btn; btn = self.host_{i}")
                btn.clicked.connect(lambda x: print(i))
    

    This is the output:
    70b49188-81d2-4fd5-8313-a7110e0ab7e2-image.png

    These are all the btn created:
    bbf20343-bb7e-4057-9604-9ebbc19f738a-image.png


  • Lifetime Qt Champion

    Hi,

    Because the value of i is going to be the last one. You have to use the second version where it is captured in the x parameter.

    On a side note, having a hundred button like that is likely not the best way to make a GUI.

    Can you explain your goal ?



  • @Black-Cat said in Detect if a button has been pressed (100 buttons):

    btn.clicked.connect(lambda x: print(i))

    You were supposed to try the alternatives :) Change to:

    btn.clicked.connect(lambda checked, x=i : self.onButtonClicked(x))
    

    I think, untested.

    Separately, you should also think about what @SGaist is saying.



  • currently the function are working, thank u guys for attention :)


  • Lifetime Qt Champion

    There's a FAQ for the behaviour you saw with the lambda.


Log in to reply