Detect if a button has been pressed (100 buttons)
-
@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)
-
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:
These are all the btn created:
-
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.